- Feature #10: Path-Based Graphics and the Nonzero Winding Rule
- Feature #9: Hit Detection
- Feature #8: canvas Is an HTML Element
- Feature #7: Temporary Drawing
- Feature #6: Offscreen Canvases
- Feature #5: Transforming the Coordinate System
- Feature #4: Image Manipulation
- Feature #3: Drawing Images and More with drawImage()
- Feature #2: The Clipping Region
- Feature #1: New Functionality in the 2D API
- Conclusion
Feature #7: Temporary Drawing
It's often useful to draw into a canvas temporarily. For example, the application in Figure 5 draws polygons and guide wires interactively as the user drags the mouse to create a new polygon. When the user releases the mouse button, the application finalizes the polygon and erases the guide wires.
Figure 5 Drawing temporary annotations into an HTML5 Canvas.
Here's the application's JavaScript for saving and restoring the drawing surface:
var drawingSurfaceImageData; function saveDrawingSurface() { drawingSurfaceImageData = context.getImageData(0, 0, canvas.width, canvas.height); } function restoreDrawingSurface() { context.putImageData(drawingSurfaceImageData, 0, 0); }
To draw into the canvas temporarily, the application takes a snapshot of the entire canvas with getImageData() when the mouse is pressed, and it repeatedly restores that snapshot as the user drags the mouse, which effectively erases the polygon and guide wires. All of these changes are accomplished with the 2D context's getImageData() and putImageData(), which are useful for more than temporary drawing. (I discuss these features in the later section "Feature #4: Image Manipulation.")