Home > Articles > Web Development > HTML/CSS

  • Print
  • + Share This
This chapter is from the book

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

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();
};
  • + Share This
  • 🔖 Save To Your Account