HTML
Using HTML 5 Canvas To Draw Over A Web Page – Part 3
April 19, 2009
1


For your reference, here’s Part 1 and Part 2.

If the example doesn’t work, it was because Part 1 and 2 uses the same variables. Open this guide as a separate page to fix it. Also remember that you need a browser that supports Canvas, such as Firefox 3.

Before you start drawing lines, you should use: beginPath() function. To draw a line into the canvas, we can use lineTo(x, y) function, followed by stroke() function. These functions are applied to the context of the canvas and takes the x and y coordinate of the end-point as parameters. lineTo draws from the previous end-point, so each subsequent lineTo continues from the previous end-point position. To specify the first point, you can use moveTo(x, y).

Line attributes can be set using strokeStyle (takes css-styled color value) and lineWidth (takes a number).

Let’s see an example. First, I created a div of 300×300 pixels.


Then, let’s attach a canvas on it, which I made yellow with rgba(255,255,0,1). Then, we draw a line from (50,50) to (150, 150) with thickness of 4 and set the stroke color to green. The code would be like this. (Note: createCanvasOverlay was explained in Part 2 of the tutorial.)


  createCanvasOverlay('rgba(255,255,0,1)', document.getElementById('myCanvas'));
  var context=myCanvas.getContext('2d');
  context.beginPath();
  context.strokeStyle='rgb(0,255,0)';  // a green line
  context.lineWidth=4;                       // 4 pixels thickness
  context.moveTo(50,50);
  context.lineTo(150,150);
  context.stroke();

Now, to make the canvas follow the mouse movement, you can attach mouseMove function to the canvasContainer (not the canvas itself).


  function onMouseMoveOnMyCanvas(event)
  {
    var mouseX=event.layerX;
    var mouseY=event.layerY;
    //alert("onMouseMove mouseX="+mouseX);
    var context = myCanvas.getContext("2d");
    if (myCanvas.pathBegun==null)
    {
      context.beginPath();
      myCanvas.pathBegun=true;
    }
    else
    {
      context.lineTo(mouseX, mouseY);
      context.stroke();
    }
  }
  document.getElementById("myCanvas").parentNode.addEventListener(
     'mousemove', onMouseMoveOnMyCanvas, false);

Click here to attach a mouse listener to the canvas, then scroll back up to the yellow canvas above to see the lines being drawn.

If the example doesn’t work, it was because Part 1 and 2 uses the same variables. Open this guide as a separate page to fix it.

On a real app, you would modify the code such as to only draw when the mouse is down, but that’s beyond the code of this tutorial.

Continued in Part 4