Web前端技术 · 第 5 课预测 · 验证 · 解释
代码实验

恢复绘图设置不等于撤销图形

save() 保存绘图设置,restore() 取回最近保存的设置;已经画到画布上的像素不会随 restore() 被撤销。擦除区域需要 clearRect()。

先判断

先不运行:最终会看到几个矩形?它们从左到右是什么颜色?

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>海报配色试验</title>
</head>
<body>
  <canvas id="poster" width="280" height="100"
    style="max-width:100%;border:1px solid">配色试验</canvas>
  <script>
    const ctx = document.querySelector('#poster').getContext('2d');
    ctx.fillStyle = 'teal';
    ctx.save();
    ctx.fillStyle = 'crimson';
    ctx.fillRect(20, 20, 100, 60);
    ctx.restore();
    ctx.fillRect(150, 20, 100, 60);
  </script>
</body>
</html>

再改一个条件

展开答案与分析

C。第一次绘制使用临时改成的深红色。restore 把 fillStyle 恢复到 save 时的青绿色,只影响后续绘制,不擦除、不重画此前的矩形。第二次 fillRect 因此使用青绿色。

观察位置:比较运行前后的图形数量,并把颜色变化与像素擦除分开解释。