检测是否以顺时针或逆时针顺序定义了数组中一组点(它们是复杂多边形的顶点)? [英] 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?

查看:75
本文介绍了检测是否以顺时针或逆时针顺序定义了数组中一组点(它们是复杂多边形的顶点)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用答案更新了,但没有绝对值符号.如果结果为正,则这些点按逆时针方向排序;如果结果为负,则按顺时针方向排序.

  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;

这篇关于检测是否以顺时针或逆时针顺序定义了数组中一组点(它们是复杂多边形的顶点)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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