An example of using DIV tags for hit testing

Written by Richard Heyes, on 16th August 2013

This page shows you an example of using DIV tags that are placed over the canvas to facilitate easy hit testing. These DIV tags are then hooked up to event listeners (eg mousemove and/or click).

[No canvas support]

If you can control the end-user environment and your use-case allows it you may find that using DIV tags can simplify your canvas hit testing greatly. It involves placing DIV tags over the canvas and assigning the event listeners to them instead of handling a click on the canvas itself. It reduces the work involved because the necessary calculations for the pointer location and whether it's over a particular shape are eliminated. The shapes that are available to you are limited to rectangles and circles (by using the border-radius: CSS property) though.


As a method for adding hit testing to your canvas it can work quite well and can save you a lot of time - if you can control the end-user environment (particularly if you have an easy way of creating DIV tags such as jQuery). But if you can't then it might not be entirely reliable (for example zooming the browser window can throw the positioning out).

    window.onload = function ()
        // Get the canvas references
        var ca = document.getElementById("cvs");
        var co = ca.getContext('2d');
        // Draw the rectangle
        co.fillStyle = 'red';
        // Draw the circle
        co.fillStyle = 'green';
        co.arc(450, 125, 50, 0, 2 * Math.PI, false);
        // Get the coordinates of the canvas tag
        var canvasXY = RGraph.getCanvasXY(ca);
        // Now create and position the square DIV tag
        var div1 = document.createElement('DIV');
   = 'absolute';
     = canvasXY[1] + 50 + 'px';
    = canvasXY[0] + 50 + 'px';
   = '100px';
   = '100px';
   = 'pointer';
            div1.onclick = function (e)
                alert('The red square has been clicked!');
        // Now create and position the circular DIV tag
        var div2 = document.createElement('DIV');
   = 'absolute';
     = canvasXY[1] + 125  - 50 + 'px';
    = canvasXY[0] + 450 - 50 + 'px';
   = '100px';
   = '100px';
   = '50px';
   = 'pointer';
            div2.onclick = function (e)
                alert('The green circle has been clicked!');