Skip to content

Instantly share code, notes, and snippets.

@anestin
Forked from isedgar/polygon-utilities-n1.js
Created February 27, 2024 13:09
Show Gist options
  • Save anestin/cfd3cd09d87d6837a65912f9e4ffe3fc to your computer and use it in GitHub Desktop.
Save anestin/cfd3cd09d87d6837a65912f9e4ffe3fc to your computer and use it in GitHub Desktop.
var polygon={
area: function(points){
var sum=0, n=points.length;
if(points[0][0] != points[n-1][0] || points[0][1] != points[n-1][1]){
sum += (points[n-1][0]*points[0][1] - points[0][0]*points[n-1][1]);
}
for(var i=0; i < n-1; ++i){
sum += (points[i][0]*points[i+1][1] - points[i+1][0]*points[i][1]);
}
return sum/2;
},
length: function(points){
var l=0, n=points.length;
if(points[0][0] != points[n-1][0] || points[0][1] != points[n-1][1]){
l += Math.sqrt(Math.pow(points[0][1] - points[n-1][1], 2) + Math.pow(points[0][0] - points[n-1][0], 2));
}
for(var i=0; i < n-1; ++i){
l += Math.sqrt( Math.pow(points[i][1] - points[i+1][1], 2) + Math.pow(points[i][0] - points[i+1][0], 2) );
}
return l;
},
is_clockwise: function(points){
// return this.area(points) < 0 ? false : true; // visual coherence
return this.area(points) < 0 ? true : false; // numerical coherence
},
centroid: function(points){
var A=this.area(points), cx=0, cy=0, n=points.length;
if(points[0][0] != points[n-1][0] || points[0][1] != points[n-1][1]){
cx += ( (points[n-1][0] + points[0][0]) * (points[n-1][0]*points[0][1] - points[0][0]*points[n-1][1]) );
cy += ( (points[n-1][1] + points[0][1]) * (points[n-1][0]*points[0][1] - points[0][0]*points[n-1][1]) );
}
for(var i=0; i < n-1; ++i){
cx += ( (points[i][0] + points[i+1][0]) * (points[i][0]*points[i+1][1] - points[i+1][0]*points[i][1]) );
cy += ( (points[i][1] + points[i+1][1]) * (points[i][0]*points[i+1][1] - points[i+1][0]*points[i][1]) );
}
return [(1/(6*A))*cx, (1/(6*A))*cy];
}
}
var points=[[123,332],[262,367],[314,500],[390,378],[465,303],[436,262],[477,123],[343,181],[222,100],[233,245]];
console.log('area: ' + polygon.area(points));
console.log('clockwise: ' + polygon.is_clockwise(points));
console.log('length: ' + polygon.length(points));
console.log('centroid: ' + polygon.centroid(points));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment