Get Distance
geometryfunctionjavascriptarchivedMeasure Coordinate Distance
It's often necessary to measure the distance between two points in 2D space. This method takes the position of the two coordinates, x1, y1 first, to x2, y2 second, and returns the distance between them.
function getDistance(x1, y1, x2, y2)
{
return (Math.abs(Math.sqrt(((x1-x2) * (x1-x2)) +
((y1-y2) * (y1-y2)))));
}
Example source code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ctx = null, game = null;
var mouseX = -1, mouseY = -1;
var circle1 = { x:250, y:150, r:70 };
var distance = 0;
window.onload = function() {
game = document.getElementById('game');
ctx = game.getContext('2d');
window.addEventListener('mousemove', function(e) {
// Get cursor position
mouseX = e.pageX;
mouseY = e.pageY;
// adjust for document offset
var p = game;
do
{
mouseX-= p.offsetLeft;
mouseY-= p.offsetTop;
p = p.offsetParent;
} while(p!=null);
// Find distance from Circles centre point to mouse cursor
distance = getDistance(circle1.x, circle1.y, mouseX, mouseY);
});
requestAnimationFrame(drawGame);
};
function getDistance(x1, y1, x2, y2)
{
return (Math.abs(Math.sqrt(((x1-x2) * (x1-x2)) +
((y1-y2) * (y1-y2)))));
}
function drawGame()
{
if(ctx==null) { return; }
// Clear Canvas
ctx.fillStyle = "#eeeeee";
ctx.fillRect(0, 0, 600, 400);
ctx.fillStyle = "#aaaacc";
ctx.strokeStyle = "#7777aa";
// Draw inner circle
ctx.beginPath();
ctx.arc(circle1.x, circle1.y, 5, 0, 2*Math.PI);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Draw outer circle
ctx.beginPath();
ctx.arc(circle1.x, circle1.y, circle1.r, 0, 2*Math.PI);
ctx.closePath();
ctx.stroke();
// Show distance
ctx.fillStyle = "#0000cc";
ctx.fillText("Cursor distance: " + distance.toFixed(3), 10, 20);
// Ask browser for next frame...
requestAnimationFrame(drawGame);
}
</script>
</head>
<body>
<p>Move your mouse around the circle to see the distance between the circles centre and the mouse itself.</p>
<p>If you do not see any circles, check your browser supports Canvas elements, and has Javascript enabled.</p>
<canvas id="game" width="600" height="400"></canvas>
</body>
</html>