我用答案更新了,但没有绝对值符号.如果结果为正,则这些点按逆时针方向排序;如果结果为负,则按顺时针方向排序.
functionpolygonArea(){var area = 0;for(var i = 0; i< vertices.length; i ++){j =(i +1)%vertices.length;面积+ =顶点[i] .x *顶点[j] .y;面积-=顶点[j] .x *顶点[i] .y;}返回面积/2;}var顺时针= polygonArea()>0;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. They can click to add vertices and hit enter to triangulate. Anyways, the algorithm works fine as long as I tell it if the points were drawn in a clockwise or counterclockwise fashion (right now I have it set only to work with clockwise polygons). I have been trying to figure this out for days, but have no idea how to determine whether the points are clockwise or counterclockwise. Try drawing shapes with the program mentioned earlier to get a better idea, you can experience what I am talking about better than I can try to explain it.
Here is how the points are defined:
function Point(x, y) { this.x = x; this.y = y; } var vertices = []; // Called on click function addPoint(mouseX, mouseY) { vertices.push(new Point(mouseX, mouseY)); }Here is an image of a clockwise polygon:
Here is an image of a counterclockwise polygon:
If you could help me figure out how to determine the "clockwise-ness" of the points, I would be very grateful!
解决方案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;
更多推荐
检测是否以顺时针或逆时针顺序定义了数组中一组点(它们是复杂多边形的顶点)?
发布评论