Home > Articles > Web Development > HTML/CSS

  • Print
  • + Share This
From the author of Feature #7: Temporary Drawing

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,

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.")

  • + Share This
  • 🔖 Save To Your Account