koko
koko

Reputation: 958

find center point of a polygon in js

I have found a nice example 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 should find the center point like so:

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

But con.centroid is undefined.

What am I doing wrong? Thanks in advance!

Upvotes: 6

Views: 6881

Answers (3)

Danilo
Danilo

Reputation: 2686

first of all you should define everything before creating your "new Contour". Moreover, centroid is a function, so you should invoke it using con.centroid() . Apparently you want that function to return a "point" but I do not think that is the correct way do to that. Take a look at this http://jsfiddle.net/SsCux/3/

PS: I think there is something wrong in the calculation of the area

Upvotes: 3

Tom Tu
Tom Tu

Reputation: 9583

Here's fixed version: jsfiddle

You've made few mistakes - first of all you've declared Contour and Point after calling them - thus you weren't able to use it. - you called centroid as if it was property and it was a function thus you were missing brackets () after centroid - in return value of centroid function you passed x and y as an Object where function point takes x and y as separate values

Upvotes: 5

xtofl
xtofl

Reputation: 41509

You call the Contour constructor way before the Contour prototype has been defined. In the said jsfiddle, move your document.write to the end, and all will go... better.

Also, you need to actually call the centroid function you defined:

var c = con.centroid();
document.write( c.x );
document.write( c.y );

Upvotes: 2

Related Questions