The CanvasRenderingContext2D.save()
method of the Canvas 2D API saves the entire state of the canvas by pushing the current state onto a stack.
On this page
CanvasRenderingContext2D: save() method
The drawing state
The drawing state that gets saved onto a stack consists of:
- The current transformation matrix.
- The current clipping region.
- The current dash list.
- The current values of the following attributes:
strokeStyle
,fillStyle
,globalAlpha
,lineWidth
,lineCap
,lineJoin
,miterLimit
,lineDashOffset
,shadowOffsetX
,shadowOffsetY
,shadowBlur
,shadowColor
,globalCompositeOperation
,font
,textAlign
,textBaseline
,direction
,imageSmoothingEnabled
.
Syntax
js
save()
Parameters
None.
Return value
None (undefined
).
Examples
Saving the drawing state
This example uses the save()
method to save the current state and restore()
to restore it later, so that you are able to draw a rect with the current state later.
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);
Result
Specifications
Specification |
---|
HTML Standard # dom-context-2d-save-dev |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
save |
1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
See also
- The interface defining this method:
CanvasRenderingContext2D
CanvasRenderingContext2D.restore()
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/save