Get distance between two points in canvas
Categories:
Calculate Distance Between Two Points on an HTML Canvas

Learn how to accurately determine the Euclidean distance between any two given points within an HTML canvas element using JavaScript.
When working with interactive graphics on an HTML canvas, a common requirement is to calculate the distance between two points. This is fundamental for various functionalities, such as collision detection, determining proximity for user interactions (e.g., hovering over an object), or pathfinding algorithms. This article will guide you through the mathematical principles and practical JavaScript implementation to achieve this.
Understanding the Euclidean Distance Formula
The standard way to calculate the distance between two points in a 2D Cartesian coordinate system (like the canvas) is using the Euclidean distance formula, derived from the Pythagorean theorem. If you have two points, P1 with coordinates (x1, y1) and P2 with coordinates (x2, y2), the distance (d) between them is given by:
flowchart LR A["Point 1 (x1, y1)"] B["Point 2 (x2, y2)"] C["Calculate Δx = x2 - x1"] D["Calculate Δy = y2 - y1"] E["Square Δx: (Δx)²"] F["Square Δy: (Δy)²"] G["Sum Squares: (Δx)² + (Δy)²"] H["Take Square Root: √((Δx)² + (Δy)²)"] I["Distance (d)"] A --> C B --> C A --> D B --> D C --> E D --> F E --> G F --> G G --> H H --> I
Flowchart illustrating the steps to calculate Euclidean distance.
The formula is: d = √((x2 - x1)² + (y2 - y1)²)
. In JavaScript, we can implement this using Math.pow()
for squaring and Math.sqrt()
for the square root.
Implementing the Distance Function in JavaScript
Let's create a reusable JavaScript function that takes the coordinates of two points and returns the distance between them. This function can then be easily integrated into your canvas applications.
/**
* Calculates the Euclidean distance between two points (x1, y1) and (x2, y2).
* @param {number} x1 - The x-coordinate of the first point.
* @param {number} y1 - The y-coordinate of the first point.
* @param {number} x2 - The x-coordinate of the second point.
* @param {number} y2 - The y-coordinate of the second point.
* @returns {number} The distance between the two points.
*/
function getDistance(x1, y1, x2, y2) {
const dx = x2 - x1; // Difference in x-coordinates
const dy = y2 - y1; // Difference in y-coordinates
// Using Math.hypot for a more robust and often faster calculation
// Math.hypot(dx, dy) is equivalent to Math.sqrt(dx*dx + dy*dy)
return Math.hypot(dx, dy);
// Alternatively, using Math.pow and Math.sqrt:
// return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}
JavaScript function to calculate the distance between two points.
Math.pow(dx, 2)
works, Math.hypot(dx, dy)
is generally preferred for calculating the hypotenuse (which is the distance in this case). It's often more numerically stable for very large or very small numbers and can be slightly more performant in some engines.Example Usage on Canvas
Here's how you might use this function within a simple canvas setup to draw two points and display the distance between them. This example assumes you have an HTML canvas element with the ID myCanvas
.
// Get the canvas element and its 2D rendering context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Define two points on the canvas
const point1 = { x: 50, y: 50 };
const point2 = { x: 200, y: 150 };
// Draw the points
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(point1.x, point1.y, 5, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(point2.x, point2.y, 5, 0, Math.PI * 2);
ctx.fill();
// Draw a line connecting the points
ctx.strokeStyle = 'black';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(point1.x, point1.y);
ctx.lineTo(point2.x, point2.y);
ctx.stroke();
// Calculate the distance
const distance = getDistance(point1.x, point1.y, point2.x, point2.y);
// Display the distance on the canvas
ctx.fillStyle = 'black';
ctx.font = '14px Arial';
ctx.fillText(`Distance: ${distance.toFixed(2)} pixels`, 10, canvas.height - 20);
console.log(`The distance between (${point1.x}, ${point1.y}) and (${point2.x}, ${point2.y}) is: ${distance.toFixed(2)}`);
Full example demonstrating distance calculation and visualization on a canvas.