HTML5 Canvas Reference - isPointInPath()








The isPointInPath() Canvas function tests whether a certain point is in the current path.

The isPointInPath() method returns true if the specified point is in the current path, otherwise false.

Browser compatibility

isPointInPath() Yes Yes Yes Yes Yes

JavaScript syntax

context.isPointInPath(x,y);

Parameter Values

Parameter Description
x The x-coordinate to test
y The y-coordinate to test




Example

The following code creates a rectangle shape and tests if the point 20,40 is in the current path:


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.rect(20, 20, 150, 100);<!--from w  w w .ja  v a  2 s . co m-->
    if (ctx.isPointInPath(20, 40)) {
        console.log("I am in");
      ctx.stroke();
    };
</script> 
</body>
</html>

The code above is rendered as follows:





Example 2

The following code creates a red circle and handles the mouse click event. It checks if the mouse is clicked inside the red circle.

Open your browser console to see the message.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
<!--from  w w  w . ja va 2s.co m-->
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.fillStyle = "red";
    ctx.arc(100,100,50, 0, Math.PI * 2, false);
    ctx.fill();
    canvas.onclick = function(e){
        console.log(ctx.isPointInPath(e.x,e.y));
    };


</script>
</body>
</html>

The code above is rendered as follows: