在js中找到多边形的中心点
我找到了一个很好的示例如何找到多边形的中心点(这里是 JS):
->请参阅这个jsfiddle示例
因此,对于这个多边形,
var polygon = [
{'x':770, 'y':400},
{'x':529, 'y':643},
{'x':320, 'y':494},
{'x':424, 'y':381},
{'x':459, 'y':369}
];
我应该像这样找到中心点:
var con = new Contour();
con.pts = polygon;
document.write(con.centroid)
但是con.centroid 是
未定义
。
我做错了什么? 提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是修复版本: jsfiddle
你犯了一些错误
- 首先,您在调用 Contour 和 Point 后声明了它们 - 因此您无法使用它。
- 您将质心称为属性,并且它是一个函数,因此您在质心之后缺少括号 ()
- 在质心函数的返回值中,您将 x 和 y 作为对象传递,其中函数点将 x 和 y 作为单独的值
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
首先,您应该在创建“新轮廓”之前定义所有内容。此外,centroid 是一个函数,因此您应该使用 con.centroid() 来调用它。显然你希望该函数返回一个“点”,但我认为这不是正确的方法。看看这个 http://jsfiddle.net/SsCux/3/
PS:我认为有面积计算有问题
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
您可以在定义
Contour
原型之前调用Contour
构造函数。在上述 jsfiddle 中,将您的document.write
移到最后,一切都会变得......更好。此外,您需要实际调用您定义的质心函数:
You call the
Contour
constructor way before theContour
prototype has been defined. In the said jsfiddle, move yourdocument.write
to the end, and all will go... better.Also, you need to actually call the
centroid
function you defined: