This library computes the convex hull of a set of points.
It uses the Graham scan algorithm.
References:
- Wikipedia
- Algorithm Archive
- This code is largely inspired by this Geeksforgeeks's post.
Copy ./lib/points.js
and ./lib/convexHull.js
files.
Point are objects with x
and y
properties representing their coordinates.
import ConvexHull from './lib/convexHull.js';
let points =[
new Point(17, 16),
new Point(35, 4),
new Point(26, 45),
new Point(43, 25),
new Point(65, 21),
];
let hull = new ConvexHull(points);
console.log(hull.getPoints());
Result :
[
Point { x: 26, y: 45 },
Point { x: 17, y: 16 },
Point { x: 35, y: 4 },
Point { x: 65, y: 21 }
]
Notes:
- The resulting points are ordered starting from the lowest left, then following the envelope clockwise.
- The path is not closed (the last point is not the same as the first).
- Optimize the code by interior elimination (or quadrilateral culling) : find the farthest points in the NW, NE, SE & SW directions and eliminate the points inside the quadrilateral they defined (as these points cannot be on the hull).
- Implement other algorithms, like Quickhull.