clearRect仅清像素不重置状态,需手动恢复globalCompositeOperation等;resetCanvas通过重设width彻底重置但性能差;fillRect仅适用于单色背景。
clearRect 是最直接的清空方式,它只擦除指定矩形区域的像素,不重置任何绘图状态。如果你之前调用了 save()、设置了 globalAlpha、strokeStyle 或 transform,这些状态依然存在——下次绘图可能颜色变淡、线条偏移、甚至被缩放。
ctx.clearRect(0, 0, canvas.width, canvas.height),别用 canvas.width 和 canvas.height 以外的尺寸,否则留白或截断style="width: 400px; height: 300px;"),要确保 canvas.width 和 canvas.height 是实际像素尺寸,否则 clearRect 会清不全beginPath(),clearRect 不受路径影响给 canvas.width 赋值(哪怕赋成当前值)会**强制清空并重置所有上下文状态**:路径、变换、样式、裁剪区域全归零。这是唯一能真正“重置”的方法,但它会触发 canvas 内存重建。
canvas.width = canvas.width 会导致明显卡顿,因为浏览器要分配新位图、丢弃旧纹理webgl 上下文,重设 width 会让 WebGL 上下文失效,需重新初始化function resetCanvas(canvas) {
const w = canvas.width;
const h = canvas.height;
canvas.width = w; // 触发重置
canvas.height = h;
}
用 fillRect 填充整个画布,在视觉上等效于清空,但它依赖你设置的 fillStyle。如果原画布有透明区域或叠加效果,这个方法反而会掩盖问题。
#fff
fillRect 前设置 ctx.fillStyle,否则按默认黑色填充globalCompositeOperation 若设为 "destination-out",fillRect 可能变成擦除而非覆盖ctx.fillStyle = "#ffffff"; ctx.fillRect(0, 0, canvas.width, canvas.height);
很多清除失败其实不是清不干净,而是后续绘图用了错误的合成模式。比如之前设了 ctx.globalCompositeOperation = "destination-out",之后没改回来,再画线就会把已有内容“挖掉”而不是覆盖。
globalCompositeOperation(默认 "source-over")、globalAlpha(默认 1.0)、lineWidth(默认 1.0)clip(),清空后裁剪路径仍生效,新内容会被裁剪——必须调用 ctx.resetClip()(Chrome/Firefox 支持)或先 save() 再 restore()