检测是否以顺时针或逆时针顺序定义了数组中一组点(它们是复杂多边形的顶点)?

编程入门 行业动态 更新时间:2024-10-17 00:22:15
本文介绍了检测是否以顺时针或逆时针顺序定义了数组中一组点(它们是复杂多边形的顶点)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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;

更多推荐

检测是否以顺时针或逆时针顺序定义了数组中一组点(它们是复杂多边形的顶点)?

本文发布于:2023-11-29 20:55:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647606.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:逆时针   多边形   顶点   组中   顺序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!