在js中找到多边形的中心点

发布于 2024-10-14 16:22:16 字数 673 浏览 3 评论 0原文

我找到了一个很好的示例如何找到多边形的中心点(这里是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

悲凉≈ 2024-10-21 16:22:16

这是修复版本: 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

始终不够 2024-10-21 16:22:16

首先,您应该在创建“新轮廓”之前定义所有内容。此外,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

最丧也最甜 2024-10-21 16:22:16

您可以在定义 Contour 原型之前调用 Contour 构造函数。在上述 jsfiddle 中,将您的 document.write 移到最后,一切都会变得......更好。

此外,您需要实际调用您定义的质心函数:

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

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 );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文