Next page | Contents page |

Event listeners

In Part 1 you may have looked at a simple drawing program, grDraw. It was suggested that you could use your browser to view the HTML source for that and also examine the JavaScript (and CSS) files used for it:

In the main JavaScript file, grDraw.js, the function start (), run by the onload event, goes like this:

function start ()
  if (!!document.createElement ("canvas").getContext)
    cnv = document.getElementById ("draw");
    g2 = cnv.getContext ("2d");
    imData = g2.getImageData (0, 0, cnv.width, cnv.height);
    g2.fillStyle = fillColour;
    g2.strokeStyle = strokeColour;
    cnv.addEventListener ("click", handleClick, false);
    cnv.addEventListener ("mousemove", handleMove, false);
    // ... the rest is not relevant for now

If the browser understands an HTML canvas element then it gets hold of that element and its graphics context, as explained earlier. After 3 lines setting a few things in the context, two event listeners are attached to the canvas element. The function for doing that, addEventListener (), is available as a method for objects representing most HTML elements. The 3 parameters passed to it are as follows.

There is more detail about these parameters on the Mozilla JavaScript reference page.

In our example two listeners are added: one for detecting mouse clicks on the canvas and one for detecting movement of the mouse while it is over the canvas.

Next page | Contents page |