CanvasRenderingContext2D: clearRect() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Canvas 2D API 的 CanvasRenderingContext2D.clearRect() 方法透過將矩形區域內的畫素設定為透明黑色來擦除它們。

注意: 請注意,如果您沒有 正確使用路徑clearRect() 可能會導致意外的副作用。請確保在呼叫 clearRect() 後開始繪製新專案之前呼叫 beginPath()

語法

js
clearRect(x, y, width, height)

clearRect() 方法將矩形區域內的畫素設定為透明。該矩形的左上角位於 (x, y),其大小由 widthheight 指定。

引數

x

矩形起始點的 x 軸座標。

y

矩形起始點的 y 軸座標。

width

矩形的寬度。正值表示向右,負值表示向左。

height

矩形的高度。正值表示向下,負值表示向上。

返回值

無(undefined)。

示例

擦除整個畫布

此程式碼片段擦除了整個畫布。這通常是在動畫的每一幀開始時需要執行的操作。擦除區域的尺寸設定為等於 <canvas> 元素的 widthheight 屬性。

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

瀏覽器相容性

另見