CanvasRenderingContext2D:save() 方法

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.save() 方法用于通过将当前状态放入栈中,以保存 canvas 的完整状态。

绘制状态

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

语法

js
save()

参数

无。

返回值

无(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-save-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
save

Legend

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

Full support
Full support

参见