Determine if two rectangles overlap each other in JavaScript

Stack Overflow has a good post on determining if two rectangles are overlapping.  I used the discussed algorithm to check for an overlap and then move one away.  I’m only moving up or down depending on which rectangle is higher or lower and if it will fit in a specified areas min or max.

<script type="text/javascript">

var rectA = {x: 2, y: 5, width: 6, height: 6};
var rectB = {x: 4, y: 10, width: 6, height: 6};
var area = {min: 0, max: 100};

var overlap = rectOverlap(rectA,rectB);
alert("Does rectA and rectB overlap? " + overlap);

if(overlap)
{
if(rectA.y >= rectB.y)
{
if(increaseY(rectA.width, rectB.y + rectB.height, area.max))
{
rectA.y = rectB.y + rectB.height + 1;
}
else if (rectA.y - rectB.height > area.min)
{
rectB.y = rectA.y - rectB.height;
}
}
else
{
if(increaseY(rectB.width, rectA.y + rectA.height, area.max))
{
rectB.y = rectA.y + rectA.height + 1;
}
else if (rectB.y - rectA.height > area.min)
{
rectA.y = rectB.y - rectA.height;
}
}
}

alert("Does rectA and rectB overlap? " + rectOverlap(rectA,rectB));

function increaseY(width, bottomEdge, Max)
{
return (bottomEdge + width < Max);
}

function valueInRange(value, min, max)
{

return (value <= max) && (value >= min);

}

function rectOverlap(A, B)
{
var xOverlap = valueInRange(A.x, B.x, B.x + B.width) ||
valueInRange(B.x, A.x, A.x + A.width);

var yOverlap = valueInRange(A.y, B.y, B.y + B.height) ||
valueInRange(B.y, A.y, A.y + A.height);

return xOverlap && yOverlap;
}

</script>

This entry was posted in JavaScript. Bookmark the permalink.

2 Responses to Determine if two rectangles overlap each other in JavaScript

  1. Thanks. I have just spent the last few hours trying to get this working… your example was spot on!

  2. ihculc says:

    thanks. this works perfectly. ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>