可以将画笔不同时刻的状态记录下来,然后保存到一个栈里面存储,后面可以在栈里面恢复画笔的状态,继续使用之前的状态绘制,效果如下:将红色,蓝色,黄色的状态都存储起来了,然后逐个恢复状态,就可以画出黄色,蓝色。红色的矩形:

源代码:
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>保存和恢复画笔状态title>
- head>
- <body>
- <div>保存和恢复画笔状态div>
- <canvas id="canvas" width="800" height="800">canvas>
- <script>
- // 获取画笔
- const canvas = document.getElementById('canvas')
- const context = canvas.getContext('2d')
-
- // 画一个红色的矩形
- context.fillStyle = 'red'
- context.fillRect(0, 0, 100, 100)
- // 保存画笔状态
- context.save()
-
- // 画一个蓝色的矩形
- context.fillStyle = 'blue'
- context.fillRect(100, 100, 100, 100)
- // 保存画笔状态
- context.save()
-
- // 画一个黄色的矩形
- context.fillStyle = 'yellow'
- context.fillRect(200, 200, 100, 100)
- context.save()
-
- // 恢复画笔的状态:此时就会再使用黄色画笔绘制一个矩形出来
- context.restore()
- context.fillRect(300, 300, 100, 100)
-
- // 恢复画笔的状态:此时会再使用蓝色的画笔绘制一个矩形出来
- context.restore()
- context.fillRect(400, 400, 100, 100)
- script>
- body>
- html>