- 1.1. The canvas Element
- 1.2. Canvas Contexts
- 1.3. Canonical Examples in This Book
- 1.4. Getting Started
- 1.5. Fundamental Drawing Operations
- 1.6. Event Handling
- 1.7. Saving and Restoring the Drawing Surface
- 1.8. Using HTML Elements in a Canvas
- 1.9. Printing a Canvas
- 1.10. Offscreen Canvases
- 1.11. A Brief Math Primer
- 1.12. Conclusion
1.7. Saving and Restoring the Drawing Surface
In Section 1.2.2, “Saving and Restoring Canvas State,” on p. 11, you saw how to save and restore a context’s state. Saving and restoring context state lets you make temporary state changes, which is something you will do frequently.
Another essential feature of the Canvas context is the ability to save and restore the drawing surface itself. Saving and restoring the drawing surface lets you draw on the drawing surface temporarily, which is useful for many things, such as rubber bands, guidewires, or annotations. For example, the application shown in Figure 1.15 and discussed in Section 2.13.1, “Translating, Scaling, and Rotating,” on p. 171, lets users interactively create polygons by dragging the mouse.
Figure 1.15. Drawing guidewires
On a mouse down event, the application saves the drawing surface. As the user subsequently drags the mouse, the application continuously restores the drawing surface to what it was when the mouse went down and then draws the polygon and the associated guidewires. When the user releases the mouse, the application restores the drawing surface one last time and draws a final representation of the polygon, without guidewires.
The JavaScript from the application shown in Figure 1.15 that pertains to drawing the guidewires is listed in Example 1.7. See Section 2.11.1, “Polygon Objects,” on p. 147 for a more complete listing of the application.
Example 1.7. Drawing guidewires by saving and restoring the drawing surface
var
canvas=
document.
getElementById
(
'canvas'
),
context=
canvas.
getContext
(
'2d'
),
... // Save and restore drawing surface...................................function
saveDrawingSurface
()
{
drawingSurfaceImageData=
context.
getImageData
(
0
,
0
,
canvas.
width,
canvas.
height);
}
function
restoreDrawingSurface
()
{
context.
putImageData
(
drawingSurfaceImageData,
0
,
0
);
}
// Event handlers..................................................... canvas.
onmousedown=
function
(
e)
{
...saveDrawingSurface
();
...}
;
canvas.
onmousemove=
function
(
e)
{
var
loc=
windowToCanvas
(
e);
if
(
dragging)
{
restoreDrawingSurface
();
...if
(
guidewires)
{
drawGuidewires
(
mousedown.
x,
mousedown.
y);
}
}
}
;
canvas.
onmouseup=
function
(
e)
{
...restoreDrawingSurface
();
}
;