CanvasRenderingContext2D: clearRect() 方法
Canvas 2D API 的 CanvasRenderingContext2D.clearRect() 方法透過將矩形區域內的畫素設定為透明黑色來擦除它們。
注意: 請注意,如果您沒有 正確使用路徑,clearRect() 可能會導致意外的副作用。請確保在呼叫 clearRect() 後開始繪製新專案之前呼叫 beginPath()。
語法
js
clearRect(x, y, width, height)
clearRect() 方法將矩形區域內的畫素設定為透明。該矩形的左上角位於 (x, y),其大小由 width 和 height 指定。
引數
返回值
無(undefined)。
示例
擦除整個畫布
此程式碼片段擦除了整個畫布。這通常是在動畫的每一幀開始時需要執行的操作。擦除區域的尺寸設定為等於 <canvas> 元素的 width 和 height 屬性。
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
擦除畫布的一部分
此示例在黃色的背景上繪製了一個藍色的三角形。然後,clearRect() 方法會擦除畫布的一部分。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
擦除的區域是矩形,其左上角位於 (10, 10)。擦除區域的寬度為 120,高度為 100。
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Draw yellow background
ctx.beginPath();
ctx.fillStyle = "#ffff66";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw blue triangle
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.moveTo(20, 20);
ctx.lineTo(180, 20);
ctx.lineTo(130, 130);
ctx.closePath();
ctx.fill();
// Clear part of the canvas
ctx.clearRect(10, 10, 120, 100);
結果
規範
| 規範 |
|---|
| HTML # dom-context-2d-clearrect-dev |
瀏覽器相容性
載入中…