How to check if point is in polygon in Javascript

2019-04-01 20:02发布

问题:

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: 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?.

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
}

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?

Thanks

回答1:

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

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;
}