Home » C++ » Fast rectangle to rectangle intersection

# Fast rectangle to rectangle intersection

Questions:

What’s a fast way to test if 2 rectangles are intersecting?

A search on the internet came up with this one-liner (WOOT!), but I don’t understand how to write it in Javascript, it seems to be written in an ancient form of C++.

``````struct
{
LONG    left;
LONG    top;
LONG    right;
LONG    bottom;
} RECT;

bool IntersectRect(const RECT * r1, const RECT * r2)
{
return ! ( r2->left > r1->right
|| r2->right < r1->left
|| r2->top > r1->bottom
|| r2->bottom < r1->top
);
}
``````

This is how that code can be translated to JavaScript. Note that there is a typo in your code, and in that of the article, as the comments have suggested. Specifically `r2->right left` should be `r2->right < r1->left` and `r2->bottom top` should be `r2->bottom < r1->top` for the function to work.

``````function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
``````

Test case:

``````var rectA = {
left:   10,
top:    10,
right:  30,
bottom: 30
};

var rectB = {
left:   20,
top:    20,
right:  50,
bottom: 50
};

var rectC = {
left:   70,
top:    70,
right:  90,
bottom: 90
};

intersectRect(rectA, rectB);  // returns true
intersectRect(rectA, rectC);  // returns false
``````

Questions:
``````function intersect(a, b) {
return (a.left <= b.right &&
b.left <= a.right &&
a.top <= b.bottom &&
b.top <= a.bottom)
}
``````

This assumes that the `top` is normally less than `bottom` (i.e. that `y` coordinates increase downwards).

Questions:

This is how the .NET Framework implements Rectangle.Intersect

``````public bool IntersectsWith(Rectangle rect)
{
if (rect.X < this.X + this.Width && this.X < rect.X + rect.Width && rect.Y < this.Y + this.Height)
return this.Y < rect.Y + rect.Height;
else
return false;
}
``````

Or the static version:

``````public static Rectangle Intersect(Rectangle a, Rectangle b)
{
int x = Math.Max(a.X, b.X);
int num1 = Math.Min(a.X + a.Width, b.X + b.Width);
int y = Math.Max(a.Y, b.Y);
int num2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if (num1 >= x && num2 >= y)
return new Rectangle(x, y, num1 - x, num2 - y);
else
return Rectangle.Empty;
}
``````

Questions:

Another more simple way. (This assumes the y-axis increases downwards).

``````function intersect(a, b) {
return Math.max(a.left, b.left) < Math.min(a.right, b.right) &&
Math.max(a.top, b.top) < Math.min(a.bottom, b.bottom);
}
``````

The 4 numbers (max’s and min’s) in the condition above also give the intersection points.

Questions: