如何在JavaScript中找到凹形不规则多边形的质心?

编程入门 行业动态 更新时间:2024-10-25 18:25:27
本文介绍了如何在JavaScript中找到凹形不规则多边形的质心?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在JavaScript中找到凹顶不规则多边形的质心?

How can you find the centroid of a concave irregular polygon given its vertices in JavaScript?

我想将一组x,y点传递给JavaScript函数并给出一个x,y点。

I want to pass a set of x,y points to a JavaScript function and be given an x,y point.

var my_points = [{x:3,y:1},{x:5,y:8},{x:2,y:9}]; function get_polygon_centroid(points){ // answer } var my_centroid = get_polygon_centroid(my_points);

my_points 变量只能代表要给出的点的格式,不表示要给出的具体点数。

The my_points variable is only supposed to represent the format of the points to be given, not to represent the specific count of points to be given.

质心返回将是多边形内的某个点。

The centroid returned will be a point somewhere inside the polygon.

最终目标是在Google Maps V3应用程序中的多边形的质心处添加标记。

The end goal would be to add a marker at the centroid of a polygon in a Google Maps V3 application.

推荐答案

对于2D表面的质心(可能是你需要的),最好的是从一些数学知识开始。

For the centroid of the 2D surface (which is likely to be what you need), The best is to start with a little bit of maths.

我在这里根据你自己的符号进行了调整:

I adapted it here to your own notation :

function get_polygon_centroid(pts) { var first = pts[0], last = pts[pts.length-1]; if (first.x != last.x || first.y != last.y) pts.push(first); var twicearea=0, x=0, y=0, nPts = pts.length, p1, p2, f; for ( var i=0, j=nPts-1 ; i<nPts ; j=i++ ) { p1 = pts[i]; p2 = pts[j]; f = p1.x*p2.y - p2.x*p1.y; twicearea += f; x += ( p1.x + p2.x ) * f; y += ( p1.y + p2.y ) * f; } f = twicearea * 3; return { x:x/f, y:y/f }; }

更多推荐

如何在JavaScript中找到凹形不规则多边形的质心?

本文发布于:2023-07-27 16:08:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1223311.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:质心   凹形   多边形   不规则   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!