CanvasRenderingContext2D.clearRect()

Canvas 2D API 的 CanvasRenderingContext2D.clearRect() 方法可以設定指定矩形(經由坐標 (x, y) 及大小 (width, height))範圍內的所有像素為透明,清除所有先前繪製的內容。

語法

void ctx.clearRect(x, y, width, height);

參數

x

The x axis of the coordinate for the rectangle starting point.

y

The y axis of the coordinate for the rectangle starting point.

width

The rectangle's width.

height

The rectangle's height.

Usage notes

A common problem with clearRect is that it may appear it does not work when not using paths properly. Don't forget to call beginPath() (en-US) before starting to draw the new frame after calling clearRect.

範例

Using the clearRect method

This is just a simple code snippet which uses the clearRect method.

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(200, 20);
ctx.lineTo(120, 120);
ctx.closePath(); // draws last line of the triangle
ctx.stroke();

ctx.clearRect(10, 10, 100, 100);

// clear the whole canvas
// ctx.clearRect(0, 0, canvas.width, canvas.height);

Edit the code below and see your changes update live in the canvas:

規範

Specification
HTML Standard
# dom-context-2d-clearrect-dev

瀏覽器相容性

BCD tables only load in the browser

參見