为何Canvas Context的save/restore方法无法移除绘制的矩形?
Canvas Context save/restore 方法的误区修正
你对save()和restore()的功能理解完全错了——这两个方法不会操作画布上已绘制的像素内容,它们只负责保存和恢复绘图上下文的状态设置,比如:
- 填充/描边样式(
fillStyle、strokeStyle) - 变换矩阵(平移、旋转、缩放)
- 线宽、全局透明度等绘图参数
你的代码里,调用restore()只是把fillStyle恢复成了之前的红色,但已经画到画布上的蓝色矩形是像素级的内容,不会被自动移除。
正确使用 save/restore 的示例
下面的代码展示了这两个方法的实际作用:恢复绘图样式,而不是删除已画图形:
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // 绘制红色矩形 ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 50, 50); // 保存当前上下文状态(此时fillStyle为red) ctx.save(); // 修改样式绘制蓝色矩形 ctx.fillStyle = 'blue'; ctx.fillRect(70, 10, 50, 50); // 恢复之前的上下文状态(fillStyle变回red) ctx.restore(); // 现在绘制的第三个矩形会是红色 ctx.fillRect(130, 10, 50, 50);
运行后画布上会有三个矩形:红、蓝、红——restore()只影响后续的绘图样式,对已经画好的蓝色矩形没有任何影响。
如果要移除已绘制的图形
如果想实现“撤销蓝色矩形”的效果,需要手动保存画布的像素数据,再恢复:
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // 绘制红色矩形 ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 50, 50); // 保存当前画布的全部像素数据 const savedCanvasState = ctx.getImageData(0, 0, canvas.width, canvas.height); // 绘制蓝色矩形 ctx.fillStyle = 'blue'; ctx.fillRect(70, 10, 50, 50); // 恢复到绘制蓝色矩形之前的状态(取消注释即可生效) // ctx.putImageData(savedCanvasState, 0, 0);
取消最后一行的注释后,蓝色矩形会被移除,画布回到只有红色矩形的状态。
内容的提问来源于stack exchange,提问作者Junior Developer
相关产品推荐
相关产品推荐

