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
.
示例
保存绘图状态
这是一段简单的代码片段,使用 save
方法保存默认的状态,这样,稍后你就可以使用默认的设置绘制一个矩形。
HTML
<canvas id="canvas"></canvas>
JavaScript
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);
结果
规范
Specification |
---|
HTML Standard # dom-context-2d-save-dev |
浏览器兼容性
BCD tables only load in the browser