Point in Rectangle

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 rect = { x:250, y:150, w:100, h:100 };

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

	game.addEventListener('mousemove', function(e) {
		mouseX = e.pageX;
		mouseY = e.pageY;

		// Calculate actual mouse position on Canvas
		var p = game;
		do
		{
			mouseX-= p.offsetLeft;
			mouseY-= p.offsetTop;

			p = p.offsetParent;
		} while(p!=null);

		// See if cursor is over the rectangle...
		isOver = pointInRect(mouseX, mouseY,
			rect.x, rect.y, rect.w, rect.h);
	});

	requestAnimationFrame(drawGame);
};

function pointInRect(x, y, rx, ry, rw, rh)
{
	return (x>=rx && x<=(rx+rw) && y>=ry && y<=(ry+rh));
}

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

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

	// Draw the rectangle
	ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
	ctx.strokeRect(rect.x, rect.y, rect.w, rect.h);

	// Request the next animation frame
	requestAnimationFrame(drawGame);
}
</script>
</head>
<body>

<p>Move your mouse cursor on and off the rectangle below.</p>
<p>If you do not see a rectangle, 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.01 second(s).