mercredi 29 juin 2016

Translate script from Actionscript to Javascript

I have bben looking for a function but the only solution I found is in Actionscript but I need it in Javascript. The original post is here. The General idea is this: I have a serie of points, those points makes a polygon, then I have another point, the script should answer if the new point is inside the polygon. Here is an example from the site where I found the function showing 4 polygon that turn green when you click ouside and blue inside. =)

enter image description here

/**
* Funcion que determina si un punto(X,Y) se encuentra dentro de un poligono
* @pointList Array de puntos Ej.: Array[ (0,0) , (100,50), (34,67) ]
* @p Punto(X,Y)
*/
function insidePolygon( pointList , p )
{
   var counter = 0;
   var i;
   var xinters;
   var p1  = new punto(0,0);
   var p2 = new punto(0,0);
   var n = pointList.length;

   p1 = pointList[0];
   for (i = 1; i <= n; i++)
   {
      p2 = pointList[i % n];
      if (p.y > Math.min(p1.y, p2.y))
      {
         if (p.y <= Math.max(p1.y, p2.y))
         {
            if (p.x <= Math.max(p1.x, p2.x))
            {
               if (p1.y != p2.y) {
                  xinters = (p.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x;
                  if (p1.x == p2.x || p.x <= xinters)
                     counter++;
               }
            }
         }
      }
      p1 = p2;
   }
   if (counter % 2 == 0)
   {
      return(false);
   }
   else
   {
      return(true);
   }
}

Aucun commentaire:

Enregistrer un commentaire