Skip to content

Instantly share code, notes, and snippets.

@alenaksu
Created August 29, 2018 14:31
Show Gist options
  • Save alenaksu/4952fd5e22170fec1a4c37d9caa2c315 to your computer and use it in GitHub Desktop.
Save alenaksu/4952fd5e22170fec1a4c37d9caa2c315 to your computer and use it in GitHub Desktop.
Centroid of a polygon
export function default (polygon) {
let cx = 0, cy = 0, a = 0;
for (let i = 0, l = polygon.length; i < l; i++) {
let x0 = polygon[i].x,
x1 = polygon[(i + 1) % l].x,
y0 = polygon[i].y,
y1 = polygon[(i + 1) % l].y;
let m = (x0 * y1 - x1 * y0);
cx += (x0 + x1) * m;
cy += (y0 + y1) * m;
a += m;
}
cx /= 3 * a;
cy /= 3 * a;
return {
x: cx,
y: cy
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment