Rectangles Intersection

Example source code


<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">
var ctx = null, game = null;
var mouseX = -1, mouseY = -1;
var isOver = false;
var rect1 = { x:250, y:150, w:100, h:100 };
var rect2 = { x:150, y:250, w:80, h:40 };

window.onload = function() {
	game = document.getElementById('game');
	ctx = game.getContext('2d');

	window.addEventListener('keypress', function(e) {

		// Move second rectangle left, right, up, or down (respectively), depending on
		// arrow key pressed, providing rectangle will not move outside of Canvas bounds
		if(e.keyCode==37 && rect2.x>=5) { rect2.x-= 5; }
		else if(e.keyCode==39 && (rect2.x+rect2.w)<=595) { rect2.x+= 5; }
		if(e.keyCode==38 && rect2.y>=5) { rect2.y-= 5; }
		else if(e.keyCode==40 && (rect2.y+rect2.h)<=395) { rect2.y+= 5; }

		// Test if rectangles intersect (overlap)
		isOver = rectanglesIntersect(rect1, rect2);
	});

	requestAnimationFrame(drawGame);
};

function rectanglesIntersect(r1, r2)
{
	return (r1.x <= (r2.x + r2.w) && (r1.x + r1.w) >= r2.x &&
		r1.y <= (r2.y + r2.h) && (r1.y + r1.h) >= r2.y);
}

function drawGame()
{
	if(ctx==null) { return; }

	// Clear Canvas
	ctx.fillStyle = "#ffffff";
	ctx.fillRect(0, 0, 600, 400);

	// Set fill and stroke colours depending on whether or not rectangle intersect
	if(isOver)
	{
		ctx.fillStyle = "#ff9999";
		ctx.strokeStyle = "#ff3333";
	}
	else
	{
		ctx.fillStyle = "#aaaacc";
		ctx.strokeStyle = "#7777aa";
	}

	// Draw first (stationary) rectangle
	ctx.fillRect(rect1.x, rect1.y, rect1.w, rect1.h);
	ctx.strokeRect(rect1.x, rect1.y, rect1.w, rect1.h);

	// Draw second (user controlled) rectangle
	ctx.fillRect(rect2.x, rect2.y, rect2.w, rect2.h);
	ctx.strokeRect(rect2.x, rect2.y, rect2.w, rect2.h);

	// Ask browser for next frame...
	requestAnimationFrame(drawGame);
}
</script>
</head>
<body>

<p>Move the smaller rectangle with the arrow keys.  The colour of both rectangles will change when they intersect.</p>
<p>If you do not see any rectangles, check your browser supports Canvas elements, and has Javascript enabled.</p>

<canvas id="game" width="600" height="400"></canvas>

</body>
</html>

Page loaded in 0.008 second(s).