Detect if a set of points in an array that are the vertices of a complex polygon were defined in a clockwise or counterclockwise order?

前端 未结 5 1010
说谎
说谎 2021-02-07 05:57

EDIT: I updated the program with the answer and it works great!

I am making a program (feel free to try it out) that lets users draw polygons which it then triangulates.

5条回答
  •  北恋
    北恋 (楼主)
    2021-02-07 06:38

    Compute the polygon area using the shoelace formula, but without the absolute value sign. If the result is positive, the points are ordered counterclockwise, and if negative - clockwise.

    function polygonArea() { 
        var area = 0;
        for (var i = 0; i < vertices.length; i++) {
            j = (i + 1) % vertices.length;
            area += vertices[i].x * vertices[j].y;
            area -= vertices[j].x * vertices[i].y;
        }
        return area / 2;
    }
    var clockwise = polygonArea() > 0;
    

提交回复
热议问题