简言
学习如何使用canvas操作状态的方法。
canvas状态
CanvasRenderingContext2D 渲染环境包含了多种绘图的样式状态(属性有线的样式、填充样式、阴影样式、文本样式)。下面的方法会帮助你使用这些状态:
save() 状态保存
CanvasRenderingContext2D.save() 是 Canvas 2D API 通过将当前状态放入栈中,保存 canvas 全部状态的方法。
语法:
void ctx.save();
保存到栈中的绘制状态有下面部分组成:
- 当前的变换矩阵。
- 当前的剪切区域。
- 当前的虚线列表。
- 以下属性当前的值: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled.
示例
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Save the current state
ctx.save();
ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);
// Restore to the state saved by the most recent call to save()
ctx.restore();
ctx.fillRect(150, 40, 100, 100);
restore() 状态恢复
CanvasRenderingContext2D.restore() 是 Canvas 2D API 通过在绘图状态栈中弹出顶端的状态,将 canvas 恢复到最近的保存状态的方法。如果没有保存状态,此方法不做任何改变。
语法:
void ctx.restore();
结语
这两个方法还是比较重要的,一般搭配其他属性或方法使用。
结束了。