Created
August 29, 2018 14:31
-
-
Save alenaksu/4952fd5e22170fec1a4c37d9caa2c315 to your computer and use it in GitHub Desktop.
Centroid of a polygon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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