Point in Circle

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 circleX = 300, circleY = 200, circleR = 75;

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

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

		var p = game;
		do
		{
			mouseX-= p.offsetLeft;
			mouseY-= p.offsetTop;

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

		isOver = pointInCircle(mouseX, mouseY,
			circleX, circleY, circleR);
	});

	requestAnimationFrame(drawGame);
};

function pointInCircle(x, y, cx, cy, cr)
{
	var squareDist = ((cx - x) * (cx - x) + (cy - y) * (cy - y));
	return squareDist <= (cr * cr);
}

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

	if(isOver)
	{
		ctx.fillStyle = "#ff9999";
		ctx.strokeStyle = "#ff3333";
	}
	else
	{
		ctx.fillStyle = "#aaaacc";
		ctx.strokeStyle = "#7777aa";
	}

	ctx.beginPath();
	ctx.arc(circleX, circleY, circleR, 0, 2*Math.PI);
	ctx.stroke();
	ctx.fill();

	requestAnimationFrame(drawGame);
}
</script>
</head>
<body>

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