如何在JavaScript中找到凹形不规则多边形的质心? [英] How can you find the centroid of a concave irregular polygon in JavaScript?

查看:457
本文介绍了如何在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中找到凹形不规则多边形的质心?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆