Skip to content

Instantly share code, notes, and snippets.

@dcousineau
Created November 15, 2011 17:16
Show Gist options
  • Save dcousineau/1367663 to your computer and use it in GitHub Desktop.
Save dcousineau/1367663 to your computer and use it in GitHub Desktop.
RaphaëlJs approximate centroid extension, should work with arbitrary paths.
Raphael.el.getCentroid = function() {
var centroid = { x: 0, y: 0 }
, area = 0
, length = this.getTotalLength()
, lengthSegment = length / 100.00;
for (var i = 0; i < length; i += lengthSegment) {
var curr = this.getPointAtLength(i)
, next = this.getPointAtLength(i + lengthSegment);
centroid.x += (curr.x + next.x) * (curr.x*next.y - next.x*curr.y);
centroid.y += (curr.y + next.y) * (curr.x*next.y - next.x*curr.y);
area += (curr.x*next.y - next.x*curr.y);
}
area = area / 2.0;
centroid.x = centroid.x / (6 * area);
centroid.y = centroid.y / (6 * area);
return centroid;
};
@mroloux
Copy link

mroloux commented Jan 3, 2014

Very useful, thank you. Needed that for https://seats.io

@Mtillmann
Copy link

very good indeed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment