Canvas——画笔状态的保存与恢复

画笔的状态是可以进行存储的,存储结构是栈结构,先进后出:
在这里插入图片描述
使用:
画笔.save() 画笔进栈
画笔.restore() 画笔出栈

eg:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!--  -->
    <canvas
      id="canvas1"
      width="600"
      height="600"
      style="background: lightgray"
    ></canvas>

    <script>
      // 找到画布
      var canvas1 = document.getElementById("canvas1");
      // 获取画笔(这里是2d画笔)
      var ctx = canvas1.getContext("2d");
      // 绘制图形
      ctx.fillStyle = "red";
      ctx.fillRect(0, 0, 100, 100);
      ctx.save();

      ctx.fillStyle = "yellow";
      ctx.fillRect(100, 100, 100, 100);
      ctx.save();

      ctx.fillStyle = "blue";
      ctx.fillRect(200, 200, 100, 100);
      ctx.save();

      ctx.restore();
      ctx.fillRect(300, 300, 100, 100);

      ctx.restore();
      ctx.fillRect(400, 400, 100, 100);

      ctx.restore();
      ctx.fillRect(500, 500, 100, 100);
    </script>
  </body>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mantou_riji/article/details/128713475