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:
xxxxxxxxxx
1
var canvas = document.querySelector('#my-canvas');
2
3
var context = canvas.getContext('2d');
4
5
context.isPointInPath(10, 10); // isPointInPath(x, y)
In this example, we present how to use isPointInPath()
method to check if a point is within the current path (square).
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas" width="200" height="200"></canvas>
12
<script>
13
14
var canvas = document.querySelector('#my-canvas');
15
var context = canvas.getContext('2d');
16
17
context.strokeStyle = '#28a745';
18
context.rect(20, 20, 100, 100); // rect(x, y, width, height)
19
context.stroke();
20
21
// point A
22
console.log(context.isPointInPath(50, 50)); // true
23
24
// point B
25
console.log(context.isPointInPath(90, 90)); // true
26
27
// point C
28
console.log(context.isPointInPath(150, 150)); // false
29
30
</script>
31
</body>
32
</html>
Visualization of the points we check:

Note:
You can draw the points using
drawPoint()
method from this article.