如何在Javascript中检查点是否为多边形 [英] How to check if point is in polygon in Javascript

查看:136
本文介绍了如何在Javascript中检查点是否为多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这段C代码(我认为)应该是一个简洁的方法来检查一个点是否在(凹面或凸面)多边形内并想在我的JS程序中使用它:

I came across this piece of C code (i think) that's supposed to be a neat way to check if a point is within a (concave or convex) polygon and want to use it in my JS program:

    int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
       c = !c;
  }
  return c;
}

nvert:多边形中的顶点数。是否在末尾重复第一个顶点。

vertx,verty:包含多边形顶点的x坐标和y坐标的数组。

testx,testy:测试点的X坐标和y坐标。
(这是来自另一个Stack Overflow问题:我该怎么办?确定2D点是否在多边形内?

nvert: Number of vertices in the polygon. Whether to repeat the first vertex at the end.
vertx, verty: Arrays containing the x- and y-coordinates of the polygon's vertices.
testx, testy: X- and y-coordinate of the test point. (This is from another Stack Overflow question: How can I determine whether a 2D Point is within a Polygon?.

这将如何转化为JS?
我已经发现了我如何在JS中启动for循环

How would this translate into JS? I've already found out how I can start the for-loop in JS

j = nvert-1
for (i = 0; i < nvert; i++) {
    //The whole if thing
    j = i
}

我猜第一行中的float *可以在JS中省略。
但是我不太确定int i,j,c = 0 ;做什么或什么!c表示何时c = 0。与0相反的是什么?

And I guess that the "float *"s in the first row can just be omitted in JS. but I'm not quite sure what the "int i, j, c = 0;" does or what "!c" means when "c = 0". What's the opposite of 0?

谢谢

推荐答案

vertx和verty应该是数组,并且应该有值。用

vertx and verty should be arrays and should have the values there. Initialize them with


vertx = [];
verty = [];

vertx = []; verty = [];

那么函数很漂亮大致相同(假设它是正确的)

Then the function is pretty much the same (assuming it is correct)

function pnpoly(var nvert, var vertx, var verty, var testx, var testy).
{
  var i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
   if ( ((verty[i]>testy) != (verty[j]>testy)) &&
   (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
    c = !c;
}

这篇关于如何在Javascript中检查点是否为多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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