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

瀏覽器相容性

另見