代码推演
restore 会撤销已经画出的矩形吗?
<canvas id="art" width="300" height="160">矩形颜色对比</canvas>
<script>
const ctx = document.querySelector('#art').getContext('2d');
ctx.fillStyle = 'navy';
ctx.save();
ctx.fillStyle = 'orange';
ctx.fillRect(10, 20, 100, 80);
ctx.restore();
ctx.fillRect(130, 20, 100, 80);
</script>
提问:运行前分别判断左右矩形的颜色。restore 恢复的是绘图状态还是像素内容?如果需要擦除左侧矩形,应使用什么操作?
查看参考解析
左橙、右深蓝。restore 恢复先前保存的 fillStyle 等状态,不撤销像素;擦除指定区域使用 clearRect,再按需求重绘。