Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 257
koko Avatar asked Jan 27 '11 09:01

koko


People also ask

How do you find the center of coordinates?

If you know their coordinates, add the two x coordinates together, and divide the result by 2. This is the x coordinate of the centre.

What is polygon in Javascript?

The <polygon> element is used to create a graphic that contains at least three sides. Polygons are made of straight lines, and the shape is "closed" (all the lines connect up).


1 Answers

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

like image 156
Tom Tu Avatar answered Sep 19 '22 01:09

Tom Tu