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

前端 未结 4 1427
一向
一向 2020-12-29 07:33

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

I want to pass a set of x,y points to a JavaScript function and be giv

4条回答
  •  伪装坚强ぢ
    2020-12-29 07:52

    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

提交回复
热议问题