An example of the HTML5 canvas path functions: isPointInPath() example

This example demonstrates the isPointInPath() function which can be used for hit detection (ie check whether a point is in the path or not). Because there is only one path (currently) if you want to test multiple paths you must replay them (start the path and reconstruct it) but not call stroke() or fill() so that it isn't rendered to the screen and then use the isPointInPath() function.

With the new Path object this will be made much easier as you will be able to retain your Path objects and subsequently test them at will.

[No canvas support]
<script>
    canvas  = document.getElementById('cvs');
    context = canvas.getContext('2d');
    
    context.beginPath();
    context.rect(200,75, 200,100);
    context.rect(250,25, 100,200);
    context.fill();



    /**
    * The mousemove eventlooks after changing the pointer to the
    * hand and back.
    */
    canvas.onmousemove = function (e)
    {
        var mouseX = e.offsetX;
        var mouseY = e.offsetY;


        /**
        * The last path drawn on the canvas was the rect, so no need to redo the path
        */
        if (context.isPointInPath(mouseX, mouseY)) {
            e.target.style.cursor = 'pointer';
            return;
        }
        
        e.target.style.cursor = 'default';
    }



    /**
    * The click event fires when the WHOLE canvas is clicked. So the coordinates of the mouse need to checked
    */
    canvas.onclick = function (e)
    {
        var mouseX = e.offsetX;
        var mouseY = e.offsetY;


        /**
        * The last path drawn on the canvas was the rect, so no need to replay the path
        */
        if (context.isPointInPath(mouseX, mouseY)) {
            alert('The black cross has been clicked!');
        }
    }
</script>

« Back to article