Created
June 15, 2021 18:57
-
-
Save isedgar/714bd75503e23a719de99479b2b0c87b to your computer and use it in GitHub Desktop.
This file contains 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
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