CanvasRenderingContext2D:restore() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

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

// 保存当前状态
ctx.save();

ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);

// 恢复到最近一次调用 save() 保存的状态
ctx.restore();

ctx.fillRect(150, 40, 100, 100);

结果

规范

Specification
HTML
# dom-context-2d-restore-dev

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
restore

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见