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

浏览器兼容性

另见