CanvasRenderingContext2D:save() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Canvas 2D API 的 CanvasRenderingContext2D.save() 方法透過將當前狀態壓入堆疊來儲存畫布的整個狀態。

繪製狀態

壓入堆疊儲存的繪製狀態包括:

語法

js
save()

引數

無。

返回值

無(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-save-dev

瀏覽器相容性

另見