Skip to content Skip to sidebar Skip to footer

Point-in-rectangle Testing

I have this matrix /// as if the create a rectangle int [][] loc = { {5, 15},//(x1, y1) {5, 30}, // (x1, y2) {20, 15},// (x2, y1) {20, 30}, // (x2, y2) } // this are the

Solution 1:

A point (x, y) is inside a rectangle (x1,y1) - (x2, y2) if

(x1 <= x <= x2) and (y1 <= y <= y2)

Your code should look like this (this actually is C code, but JavaScript shouldn't be much different):

 x1 = loc[0][0];
 x2 = loc[2][0];
 y1 = loc[0][1];
 y2 = loc[2][1];
 for (int i = 0; i < num_points; i++) {
   if ((x1 <= point[i][0]) && (point[i][0] <= x2) && 
       (y1 <= point[i][1]) && (point[i][1] <= y2)) {
     // This point is inside the rectangle - insert code here
   } else {
     // This point is not inside the rectangle - insert code here
   }
 }

Note that this will only work if (x1 <= x2) and (y1 <= y2), so you might perhaps make sure by using this instead the first four lines above:

x1 = Math.Min(loc[0][0], loc[2][0]);x2 = Math.Max(loc[0][0], loc[2][0]);y1 = Math.Min(loc[0][1], loc[2][1]);y2 = Math.Max(loc[0][1], loc[2][1]);

Solution 2:

Although the question has been answered extensively, I'd like to share my piece of code because it looks more intuitive and looks more like the math I had at highschool. Just in case people look this question up because of home work :)

functionbetween(min, p, max){
  result = false;

  if ( min < max ){
    if ( p > min && p < max ){
      result = true;
    }
  }

  if ( min > max ){
    if ( p > max && p < min){
      result = true
    }
  }

  if ( p == min || p == max ){
    result = true;
  }

  return result;
}

functionpoint_in_rectagnle( x, y, left, top, right, bottom){
  result = false;

  if ( between(left,x,right) && between(top,y,bottom ) ){
    result = true;
  }
  return result;
}

Solution 3:

The code in the question is Java or C or some other language that defines array literals with {}, but since the tag is Javascript and this shows up on Google for Javascript, here is a reasonable way to do point-rectangle intersection in JS.

functionpointRectangleIntersection(p,r) {
    returnp.x>r.x1&&p.x<r.x2&&p.y>r.y1&&p.y<r.y2;
}

varpoint= {x:1, y:2};varrectangle= {x1:0, x2:10, y1:1, y2:7};pointRectangleIntersection(point,rectangle);

As mentioned in the comments, change > to >= and/or < to <= to do an intersection which includes the rectangle boundaries.

Post a Comment for "Point-in-rectangle Testing"