跳到主要内容

clearRect

2023年08月12日
柏拉文
越努力,越幸运

一、认识


ctx.clearRect()Canvas 2D API 的方法,这个方法通过把像素设置为透明以达到擦除一个矩形区域的目的。如果没有依照绘制路径的步骤,使用 clearRect() 会导致意想之外的结果。请确保在调用 clearRect() 之后绘制新内容前调用 beginPath()

二、语法


ctx.clearRect(x, y, width, height);
  • x: 矩形起点的 x 轴坐标。

  • y: 矩形起点的 y 轴坐标。

  • width: 矩形的宽度。

  • height: 矩形的高度。

三、场景


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

<script>
const canvas = document.querySelector('#canvas');
canvas.width = 500;
canvas.height = 500;
const ctx = canvas.getContext('2d');

ctx.clearRect(0, 0, canvas.width, canvas.height);
</script>

四、对比


4.1 Canvas 清除画布的方式对比

canvas.width = xxx: 无论 width 有没有变化, 只要重新赋值, 都会动态地修改画布宽度, 同时清楚画布上所有内容, 重置画布状态。canvas.width 是一个更彻底的重置画布的方式

ctx.clearRect(x,y,width,height): 用于清除画布指定矩形区域中的内容, 而不清除画布状态。通过 ctx.clearRect(0,0,canvas.width,canvas.height) 清除整个画布内容。