CanvasRenderingContext2D: restore() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Canvas 2D API 的 CanvasRenderingContext2D.restore() 方法通过弹出绘制状态栈中的顶部条目来恢复最近保存的 canvas 状态。如果没有保存的状态,此方法不执行任何操作。

有关绘制状态的更多信息,请参阅 CanvasRenderingContext2D.save()

语法

js
restore()

参数

无。

返回值

无(undefined)。

示例

恢复保存的状态

此示例使用 save() 方法保存当前状态,并使用 restore() 在稍后恢复它,以便您能够使用当前状态绘制一个矩形。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
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);

结果

规范

规范
HTML
# dom-context-2d-restore-dev

浏览器兼容性

另见