Point in Circle
geometryfunctionjavascriptarchivedTest point in circle
A simple method for testing if a given point, described by a set of coordinates in a 2D plane, falls within the area of a circle provided its X and Y coordinates and radius.
This method tests if the x (horizontal) difference squared plus the y (vertical) difference squared is less than or equal to the radius squared.
function pointInCircle(x, y, cx, cy, cr)
{
var squareDist = ((cx - x) * (cx - x) + (cy - y) * (cy - y));
return squareDist <= (cr * cr);
}
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>