Save & Restore
Next ❯Animation
- turned_in_notSave & Restore Methods
save()
restore()
- Note! Drawing state includes all the canvas 2D context methods & properties related to effects, design, text style, compositing & clipping region
save( )
Used to save the current drawing state, In simple words we create a current drawing state restore point
Syntax
ctx.save()
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = 'red';ctx.fillRect(10, 10, 40, 40);
ctx.save(); // Save the state-1
ctx.fillStyle = 'blue';ctx.fillRect(30, 30, 40, 40);
ctx.restore(); // Restore the state-1
ctx.fillRect(50, 50, 40, 40);
savesubject
saveclose
<!DOCTYPE html>
<html>
<head>
<title>Full Code</title>
</head>
<body>
<img src="/images/firefox.png" id="image">
<canvas id="canvas" width="200" height="100" style="border:1px solid teal;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
/* Now we code to draw on canvas */
ctx.fillStyle = 'red';ctx.fillRect(10, 10, 40, 40);
ctx.save(); // Save the state 1
ctx.fillStyle = 'blue';ctx.fillRect(30, 30, 40, 40);
ctx.restore(); // Restore the state 1
ctx.fillRect(50, 50, 40, 40);
</script>
</body>
</html>
restore( )
Used to restore the saved drawing state point
- It will restore from the last saved drawing state in stack (Last In First Out)
Syntax
ctx.restore()
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = 'red';ctx.fillRect(10, 10, 40, 40);
ctx.save(); // Save state-1
ctx.fillStyle = 'blue';ctx.fillRect(25, 25, 40, 40);
ctx.save(); // Save state-2
ctx.fillStyle = 'yellow';ctx.fillRect(40, 40, 40, 40);
ctx.restore(); // Restore state-2
ctx.fillRect(55, 55, 40, 40);
ctx.restore(); // Restore state-1
ctx.fillRect(70, 70, 40, 40);
restoresubject
restoreclose
<!DOCTYPE html>
<html>
<head>
<title>Full Code</title>
</head>
<body>
<img src="/images/firefox.png" id="image">
<canvas id="canvas" width="200" height="100" style="border:1px solid teal;"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
/* Now we code to draw on canvas */
ctx.fillStyle = 'red';ctx.fillRect(10, 10, 40, 40);
ctx.save(); // Save state-1
ctx.fillStyle = 'blue';ctx.fillRect(25, 25, 40, 40);
ctx.save(); // Save state-2
ctx.fillStyle = 'yellow';ctx.fillRect(40, 40, 40, 40);
ctx.restore(); // Restore state-2
ctx.fillRect(55, 55, 40, 40);
ctx.restore(); // Restore state-1
ctx.fillRect(70, 70, 40, 40);
</script>
</body>
</html>
❮ Prev ImageData
Next ❯Animation