跳到主要内容

save

2023年08月11日
柏拉文
越努力,越幸运

一、认识


ctx.save()Canvas 2D API 通过将当前状态放入栈中,保存 canvas 全部状态的方法。

二、语法


const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

ctx.save();

三、状态


保存到栈中的绘制状态有下面部分组成:

  1. 当前的变换矩阵

  2. 当前的剪切区域

  3. 当前的虚线列表

  4. 以下属性当前的值: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled.

四、场景


4.1 保存、恢复 fillStyle

使用 save() 方法保存 fillStyle 的状态,使用 restore() 进行恢复。

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "red";
// 保存当前绘制状态: 当前绘制状态为 fillStyle = red
ctx.save();
ctx.fillRect(0, 0, 100, 100);

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

// 保存之前绘制状态: 之前绘制状态为 fillStyle = red
ctx.restore();
ctx.fillRect(200, 0, 100, 100);

document.body.appendChild(canvas);

4.2 保存、恢复 translate 起始点

使用 save() 方法保存 canvas 起始点的位置,使用 restore() 进行恢复。

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");

// 保存当前 Canvas 状态, 当前状态是 (0, 0) 原点
ctx.save();

ctx.translate(50, 50);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 50, 50);

// 恢复到上一个 Canvas 状态, 即 (0, 0) 原点
ctx.restore();
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 50, 50);

document.body.appendChild(canvas);