This module has an algorithm to check if two simple polygons intersect, and another to find the intersection polygons.
For an intersection to exist, the intersection area must be > 0. In other words, the polygon interiors must intersect. For example, the orange and blue polygons do not intersect in the first case, but intersect in the second:
⠀ | ⠀ |
---|---|
![]() |
![]() |
For more examples, check below the table of tests both algortihms were submitted to.
The algorithm to check if the intersection exists was based on the observation that an intersection occurs if one of the following criteria is fulfilled:
- An edge of one polygon crosses an edge of the other;
- A point of one polygon lies inside the other;
- A point of one polygon lies on an edge of the other, in such a way that the interior of the point's corner intersects the interior of the other polygon.
The algorithm to find the intersection polygons was then designed to apply these three tests in an iterative fashion and save the points it considers to be part of the intersection polygon.
To use each algorithm, both polygons must be arrays of 2D point coordinates, ordered counter-clockise. Then, they may be called like:
const polygon1 = [[0,0],[1,0],[1,1],[0,1]];
const polygon2 = [[0,-1],[2,0.5],[0,2]];
const polygonsIntersect = checkIfPolygonsIntersect(polygon1, polygon2);
const intersectionPolygons = findIntersectionBetweenPolygons(polygon1, polygon2);