UNPKG

@thi.ng/geom-clip-poly

Version:

2D polygon clipping / offsetting (Sutherland-Hodgeman, Grainer-Hormann)

34 lines (33 loc) 1.06 kB
import { intersectLineLine } from "@thi.ng/geom-isec/line-line"; import { centroid } from "@thi.ng/geom-poly-utils/centroid"; import { EPS } from "@thi.ng/math/api"; import { corner2 } from "@thi.ng/vectors/clockwise"; const sutherlandHodgeman = (pts, bounds, bc, eps = EPS) => { bc = bc || centroid(bounds); for (let ne = bounds.length, j = ne - 1, i = 0; i < ne; j = i, i++) { const clipped = []; const ca = bounds[j]; const cb = bounds[i]; const sign = corner2(ca, cb, bc, eps); for (let np = pts.length, k = np - 1, l = 0; l < np; k = l, l++) { const p = pts[k]; const q = pts[l]; const cqsign = corner2(ca, cb, q, eps); if (corner2(ca, cb, p, eps) === sign) { clipped.push( cqsign !== sign ? intersectLineLine(ca, cb, p, q).isec[0] : q ); } else if (cqsign === sign) { clipped.push(intersectLineLine(ca, cb, p, q).isec[0], q); } } if (clipped.length < 2) { return []; } pts = clipped; } return pts; }; export { sutherlandHodgeman };