Path2D object example: Hit testing

An example of using the Path2D object to make hit testing easier

«Back to the Path2D object article

This is an example of hit testing using the Path2D object and the isPointInPath() function.

[No canvas support]
<script>
    $(document).ready(function () // jQuery
    {
        var canvas  = document.getElementById('cvs')
        var context = canvas.getContext('2d');

        // Create the shape
        var path = new Path2D();
            path.moveTo(50,50)
            path.lineTo(550,50)
            path.quadraticCurveTo(100,50,150,200)
        path.closePath()

        // Stroke and fill it
        context.strokeStyle = '#600';
        context.fillStyle = '#f00';
        context.stroke(path);
        context.fill(path);

        /**
        * The mousemove listener
        */
        canvas.addEventListener('mousemove', function (e)
        {
            var x = e.offsetX;
            var y = e.offsetY;

            if (context.isPointInPath(path, x, y)) {
                e.target.style.cursor = 'pointer';
            } else {
                e.target.style.cursor = 'default';
            }
        }, false);

        /**
        * The click listener
        */
        canvas.addEventListener('click', function (e)
        {
            var x = e.offsetX;
            var y = e.offsetY;

            if (context.isPointInPath(path, x, y)) {
                alert('Clicked!');
            }
        }, false);
    })
</script>