HTML and CSS Reference
In-Depth Information
Saving the Context State
The state of a drawing context includes the various properties such as fillStyle and strokeStyle that you have
already used. It also includes the accumulation of all transformations that have been applied. If you start using
multiple transformations, getting back to the original state may be difficult. Fortunately, the drawing context
provides the ability to save and then restore the state of the context.
The current state is saved by calling the save() function. Saving the state pushes the current state onto
a stack. Calling the restore() function pops the most recently saved state off of the stack and makes that the
current state. This is illustrated in Figure 10-8 . ); // saves State A
. . . ); // saves State B
. . . ); // saves State C
State A
State B
State C
. . .
context.restore( ); // gets State C
. . .
context.restore( ); // gets State B
. . . ); // saves State D
State A
State D
Figure 10-8. Saving and restoring the drawing context state
You should generally save the state before doing any transformations, especially complex ones. When you
have finished drawing whatever elements needed the transformation, you can restore the state back to the way it
was. Remember, changing the state by setting the fillStyle or performing a transformation does not affect what
has already been drawn.
Drawing the Solar System
With these features at your disposal, let's draw a simple model of the solar system.
eXerCISe 10-5. MODeLING the SOLar SYSteM
Open the index.cshtml file and add the canvas element shown in bold just after
the existing canvas element:
<canvas id = "board" width = "600" height = "600">
Not supported
<canvas id = "solarSystem" width = "450" height = "400">
Not supported
Search WWH ::

Custom Search