Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
save and restore MethodsThe canvasās state includes its current style and transformations, which are maintained in a stack. The save method is used to save the contextās current state. The restore method restores the context to its previous state. Figure 14.37 demonstrates using the save method to change a rectangleās fillStyle and the restore method to restore the fillStyle to the previous settings in the stack.
Ā 1Ā Ā Ā <!DOCTYPE html>
Ā 2
Ā 3Ā Ā Ā <!-- Fig. 14.37: saveandrestore.html -->
Ā 4Ā Ā Ā <!-- Saving the current state and restoring the previous state. -->
Ā 5Ā Ā Ā <html>
Ā 6Ā Ā Ā Ā Ā Ā <head>
Ā 7Ā Ā Ā Ā Ā Ā Ā Ā Ā <meta charset = "utf-8">
Ā 8Ā Ā Ā Ā Ā Ā Ā Ā Ā <title>Save and Restore</title>
Ā 9Ā Ā Ā Ā Ā Ā </head>
10Ā Ā Ā Ā Ā Ā <body>
11Ā Ā Ā Ā Ā Ā Ā Ā Ā <canvas id = "save" width = "400" height = "200">
12Ā Ā Ā Ā Ā Ā Ā Ā Ā </canvas>
13Ā Ā Ā Ā Ā Ā Ā Ā Ā <script>
14Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā function draw()
15Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā {
16Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā var canvas = document.getElementById("save");
17Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā var context = canvas.getContext("2d")
18
19Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // draw rectangle and save the settings
20Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.fillStyle = "red"
21Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.fillRect(0, 0, 400, 200);
22Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.save();
23
24Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // change the settings and save again
25Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.fillStyle = "orange"
26Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.fillRect(0, 40, 400, 160);
27Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.save();
28
29Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // change the settings again
30Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.fillStyle = "yellow"
31Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.fillRect(0, 80, 400, 120);
32
33Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // restore to previous settings and draw new rectangle
34Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.restore();
35Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.fillRect(0, 120, 400, 80);
36
37Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // restore to original settings and draw new rectangle
38Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.restore();
39Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā context.fillRect(0, 160, 400, 40);
40Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā }
41Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā window.addEventListener( "load", draw, false );
42Ā Ā Ā Ā Ā Ā Ā Ā Ā </script>
43Ā Ā Ā Ā Ā Ā </body>
44Ā Ā Ā </html>