Simplest way to calculate the intersect area of two rectangles

Solution 1:

Uses only max and min (drag the squares to see the calculation. Forget about most of the code, the calculation is those two lines with the min and max):

http://jsfiddle.net/Lqh3mjr5/

You can also reduce min to max here (or the opposite), i.e. $min\{a,b\} = -max\{-a,-b\}$.


First compute the bounding rectangles rect1 and rect2 with the following properties:

rect = {
  left: x1,
  right: x1 + x2,
  top: y1,
  bottom: y1 + y2,
}

The overlap area can be computed as follows:

x_overlap = Math.max(0, Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left));
y_overlap = Math.max(0, Math.min(rect1.bottom, rect2.bottom) - Math.max(rect1.top, rect2.top));
overlapArea = x_overlap * y_overlap;