EN
JavaScript - is point in path on canvas
0
points
In this article, we would like to show you how to check if point is in the path on canvas using JavaScript.
Quick solution:
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.isPointInPath(10, 10); // isPointInPath(x, y)
Practical example
In this example, we present how to use isPointInPath()
method to check if a point is within the current path (square).
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="200" height="200"></canvas>
<script>
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.strokeStyle = '#28a745';
context.rect(20, 20, 100, 100); // rect(x, y, width, height)
context.stroke();
// point A
console.log(context.isPointInPath(50, 50)); // true
// point B
console.log(context.isPointInPath(90, 90)); // true
// point C
console.log(context.isPointInPath(150, 150)); // false
</script>
</body>
</html>
Visualization of the points we check:
Note:
You can draw the points using
drawPoint()
method from this article.