restore
2023年08月11日
一、认识
ctx.restore()
是 Canvas 2D API
通过在绘图状态栈中弹出顶端的状态,将 canvas
恢复到最近的保存状态的方法。如果没有保存状态,此方法不做任何改变。
二、语法
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.restore();
三、场景
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);