canvas的状态如何保存和恢复
- save():保存当前的绘图状态。
- restore():恢复之前保存的绘图状态。
调用save方法将当前绘图状态保存到绘图堆栈中,每次调用restore方法从栈顶取出保存的状态。
由于出栈的次数不能多于入栈的次数,故程序中restore方法调用的次数不应该比save方法多。
save都可以保存什么?
- 当前的坐标变换信息(比如旋转rotate()或平移setTransform())
- 当前剪贴区域
- 图形上下文对象(
CanvasRenderingContext2D)的当前属性值
其中CanvasRenderingContext2D的主要属性值如下,完整请查看MDN文档:
| 属性 | 描述 |
|---|---|
| canvas | 取得画布<canvas>元素 |
| fillStyle | 填充路径的当前的颜色、模式或渐变 |
| globalCompositeOperation | 指定颜色如何与画布上已有颜色组合(合成) |
| lineCap | 指定线段端点的绘制方式 |
| lineJoin | 指定线段连接的绘制方式 |
| lineWidth | 绘制线段的宽度 |
| miterLimit | 当lineJoin为miter时,这个属性指定斜连接长度和二分之一线宽的最大比率 |
| shadowBlur | 指定阴影模糊度 |
| shadowColor | 指定阴影颜色 |
| shadowOffsetX | 指定阴影水平偏移值 |
| shadowOffsetY | 指定阴影垂直偏移值 |
| strokeStyle | 指定线段颜色 |
实例

在线查看
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
ctx.fillStyle = "#999";
ctx.fillRect(0, 0, 400, 30);
ctx.save(); // 保存当前状态 01
ctx.fillStyle = "#09F";
ctx.fillRect(0, 30, 400, 30);
ctx.save(); // 保存当前状态 02
ctx.fillStyle = "#333";
ctx.fillRect(0, 60, 400, 30);
ctx.restore(); // 取出保存的状态 02 恢复
ctx.fillRect(0, 90, 400, 30);
ctx.restore(); // 取出保存的状态 01 恢复
ctx.fillRect(0, 120, 400, 30);
