Quick transition between rectangle and rectangle

What is a quick way to check if 2 rectangles intersect?




A search on the Internet caused this one-line font (WOOT!), But I don’t understand how to write it in Javascript, it seems to be written in an ancient C ++ form.

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 ); } 
+77
c ++ javascript language-agnostic graphics
May 02 '10 at 3:32
source share
5 answers

Here's how to translate this code into JavaScript. Please note that there is a typo in your code and sentences in the article. In particular, r2->right left must be r2->right < r1->left , and r2->bottom top must 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 
+133
May 02 '10 at 3:50 a.m.
source share
 function intersect(a, b) { return (a.left <= b.right && b.left <= a.right && a.top <= b.bottom && b.top <= a.bottom) } 

This suggests that top usually smaller than bottom (i.e. that y coordinates increase down).

+61
May 02 '10 at 3:42 a.m.
source share

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(aX, bX); int num1 = Math.Min(aX + a.Width, bX + b.Width); int y = Math.Max(aY, bY); int num2 = Math.Min(aY + a.Height, bY + b.Height); if (num1 >= x && num2 >= y) return new Rectangle(x, y, num1 - x, num2 - y); else return Rectangle.Empty; } 
+18
Apr 07 '14 at 19:18
source share

Another easy way. (This assumes that the y axis is increasing downward).

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

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

+5
03 Feb '16 at 11:52
source share

This is a type of Rect that you can use. This is already JavaScript.

https://dxr.mozilla.org/mozilla-beta/source/toolkit/modules/Geometry.jsm

+1
Sep 21 '16 at 17:46
source share



All Articles