Using HTML 5 Canvas To Draw Over A Web Page – Part 4
May 7, 2009

Building from Part 1, 2, and 3, we’re now ready to create a canvas overlay that sits above a html page, and where user can draw on.  Here are the steps that we will use:

  • Step 1: Create the canvas.
  • Step 2: Create a function that draws on the canvas based on the mouse position.
  • Step 3: Attach mouse move event listener to the canvas (we are actually going to attach the listener to the div that contains the canvas.

Step 1: Create the canvas

As explained in Part 1 and 2 of the tutorial, we can create a canvas programatically.  Since the canvas will cover the entire web-page, and we want the code to be re-usable, we are going to use the function created in Part 2 to create the canvas.



The color is set to alpha value of 0, which means the canvas will be transparent, so you can still see what is behind the canvas.
The canvasContainer is set to none, which means the canvas will be added to a dynamically created div which covers the entire html.

Step 2: Create a function that draws on the canvas based on the mouse position.

This is explained in Step 3, but here, we’re going to make it so that a click is required to start and stop drawing. The click handler is shown below as onMouseClickOnMyCanvas. The variable drawing indicates whether the mouse is on the drawing mode.

  function onMouseMoveOnMyCanvas(event)
    if (myCanvas.drawing)
      var mouseX=event.layerX;
      var mouseY=event.layerY;

      var context = myCanvas.getContext("2d");
      if (myCanvas.pathBegun==false)
        context.lineTo(mouseX, mouseY);

  function onMouseClickOnMyCanvas(event)
    // reset the path when starting over
    if (myCanvas.drawing)

Step 3

We attach the mouse handler to the canvas in the createCanvasOverlay function (and while at it, we also set the line thickness to 4, and the color to green). In a real application, these customization code should be modularized, but this is sufficient for illustration purpose:

 function createCanvasOverlay(color, canvasCothntainer)
     // existing code truncated
     context.strokeStyle='rgb(0,255,0)';  // a green line
     context.lineWidth=4;                 // 4 pixels thickness
     myCanvas.parentNode.addEventListener('mousemove', onMouseMoveOnMyCanvas, false);
     myCanvas.parentNode.addEventListener('mousedown', onMouseClickOnMyCanvas, false);

You can try a demo by clicking here. Remember that your browser must support Canvas. There is a CLOSE button on the top-left of the canvas (scroll up if it’s not visible). Click to start drawing, and click again to stop drawing.

Source files: