I have some SVG arbitrary closed shapes composed of lines and curve paths. I want to check if some points are inside the shape. I have found Point in Polygon algorithm that seems to work well, but I will have to decompose my path into a multitude of lines. Is there a more direct solution to this problem? If not, what good algorithm I can use to decompose my paths?
Advertisement
Answer
Let me demonstrate how to use isPointInFill
by this live code.
JavaScript
x
51
51
1
/*
2
https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/isPointInFill
3
*/
4
5
const circle = document.getElementById("circle1");
6
7
try {
8
// Point not in circle
9
console.log("Point at 10,10:", circle.isPointInFill(new DOMPoint(10, 10)));
10
11
// Point in circle but not stroke
12
console.log("Point at 40,30:", circle.isPointInFill(new DOMPoint(40, 30)));
13
14
// Point in circle stroke
15
console.log("Point at 83,17:", circle.isPointInFill(new DOMPoint(83, 17)));
16
} catch (e) {
17
// for the browsers that still support the deprecated interface SVGPoint
18
let tof = false;
19
const svg = document.getElementsByTagName("svg")[0];
20
const point = svg.createSVGPoint();
21
if (tof == true) {
22
document.getElementById("p1").setAttribute("fill", "red");
23
}
24
// Point not in circle
25
point.x = 10;
26
point.y = 10;
27
tof = circle.isPointInFill(point);
28
console.log("Point at 10,10:", tof);
29
if (tof == true) {
30
document.getElementById("p1").setAttribute("fill", "red");
31
}
32
33
// Point in circle but not stroke
34
point.x = 40;
35
point.y = 30;
36
tof = circle.isPointInFill(point);
37
console.log("Point at 40,30:", tof);
38
if (tof == true) {
39
document.getElementById("p2").setAttribute("fill", "red");
40
}
41
42
// Point in circle stroke
43
point.x = 83;
44
point.y = 17;
45
tof = circle.isPointInFill(point);
46
console.log("Point at 83,17:", tof);
47
if (tof == true) {
48
document.getElementById("p3").setAttribute("fill", "red");
49
}
50
} //end_catch
51
//EOF
JavaScript
1
21
21
1
<svg
2
viewBox="0 0 100 100"
3
width="150"
4
height="150"
5
xmlns="http://www.w3.org/2000/svg">
6
<style>
7
svg { background-color: lightgray; }
8
#circle1 { fill: #FFDDDD; }
9
</style>
10
<circle
11
id="circle1"
12
cx="50"
13
cy="50"
14
r="45"
15
stroke="black"
16
stroke-width="10" />
17
18
<circle id="p1" cx="10" cy="10" r="5" fill="seagreen" />
19
<circle id="p2" cx="40" cy="30" r="5" fill="seagreen" />
20
<circle id="p3" cx="83" cy="17" r="5" fill="seagreen" />
21
</svg>
If isPointInStroke
is used instead, the third point will be the one that turns to red.