HTML and CSS Reference
context object offers two methods : save() and restore() . As their names suggest, the save() method
saves a canvas state, whereas the restore() method restores a previously saved state.
Using the save() and restore() Methods
Using save() and restore() is relatively straightforward. The save() method pushes a snapshot of the
canvas state onto a stack, whereas the restore() method pops a saved snapshot of the canvas state. It's
important to remember that canvas state doesn't refer to the actual drawing on the canvas. Listing 4-19
show how you use save() and restore() .
Listing 4-19. Using the save() and restore() Methods
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
context.lineWidth = 5;
context.fillStyle = 'blue';
context.fillRect(10, 120, 150, 50);
context.lineWidth = 10;
context.fillStyle = 'red';
context.fillRect(20, 130, 150, 50);
context.fillRect(30, 140, 150, 50);
As you can see, first canvas settings such as lineWidth and fillStyle are set and a rectangle is drawn.
You save these settings using the save() method. Next, you change the canvas settings to new values, and a
rectangle is drawn. Finally, before drawing a third rectangle, you restore the canvas settings using
restore() . Figure 4-22 shows the effect of saving and restoring the canvas state.
Figure 4-22. Effect of saving and restoring the canvas state