The isPointInPath function

The isPointInPath function can be used to determine if the coordinates that you give it are contained within the current path or not. It only determines the current path so if you have multiple shapes that you want to test you will need to replay the paths but not stroke or fill them (so that they're not drawn onto the canvas) and then use the isPointInPath function each time. The isPointInPath function can be used to determine hits for complex shapes that involve angles or curves. For example, the Funnel chart and drawing api Marker1 objects use the function to facilitate hit testing.

The function only gives you a true or false as to whether the coordinates that you give it are in the path. So you need to create your own functions to get the mouse coordinates and also take the relevant action should the point that you give it be in the current path.


Arguments to the function

The isPointinPath function can take two or three arguments:

context.isPointInPath(path, x, y)
context.isPointInPath(x, y)

An example

<script>
    window.onload = function ()
    {
        var canvas  = document.getElementById("cvs");
        var context = canvas.getContext('2d');
    
        // Draw something on the canvas
        context.beginPath();
        context.rect(25,25,50,50);
        context.fill();
    
        // Install a mousemove event listener onto the canvas
        canvas.onmousemove = function (e)
        {
            var canvas = e.target;
            var context = canvas.getContext('2d');
    
            // This gets the mouse coordinates (relative to the canvas). It uses the RGraph.getMouseXY(event)
            // function
            var mouseXY = RGraph.getMouseXY(e);
            var mouseX  = mouseXY[0];
            var mouseY  = mouseXY[1];
    
    
            // Because the rect was the last path drawn onto the canvas theres no need to replay it
            if (context.isPointInPath(mouseX, mouseY)) {
                canvas.style.cursor = 'pointer';
                return;
            }
    
            canvas.style.cursor = 'default';
        }
    }
</script>

See also