Find the center point of a polygon in js

I found a good example of how to find the center point of a polygon ( and here in JS ):

-> See this jsfiddle example

So with this polygon

var polygon = [ {'x':770, 'y':400}, {'x':529, 'y':643}, {'x':320, 'y':494}, {'x':424, 'y':381}, {'x':459, 'y':369} ]; 

I have to find the center like this:

 var con = new Contour(); con.pts = polygon; document.write(con.centroid) 

But con.centroid is undefined .

What am I doing wrong? Thanks in advance!

+6
javascript prototype canvas
source share
3 answers

You call the Contour constructor before the Contour prototype. In the specified jsfiddle, move your document.write to the end and everything will be ... better.

In addition, you need to actually call the centroid function that you defined:

 var c = con.centroid(); document.write( cx ); document.write( cy ); 
+2
source share

Here's the fixed version: jsfiddle

You made a few mistakes - first of all, you declared Contour and Point after calling them - so you could not use it. - you called the centroid as if it were a property, and it was a function, so you did not have the brackets () after the centroid - in the return value of the centroid function, you passed x and y as an object, where the function point takes x and y as separate values

+5
source share

First of all, you must define everything before creating your β€œnew circuit”. In addition, centroid is a function, so you should call it with con.centroid() . Apparently you want this function to return a "dot", but I don't think this is the right way. Take a look at this http://jsfiddle.net/SsCux/3/

PS: I think that something is wrong in calculating the area

+3
source share

All Articles