Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get distance between two points in canvas

People also ask

How do you find the distance between two points in JavaScript?

function getDistance(xA, yA, xB, yB) { var xDiff:Number = xA - xB; var yDiff:Number = yA - yB; return Math. sqrt(xDiff * xDiff + yDiff * yDiff); } var distance = getDistance(0, 0, 100, 100); alert(distance); That's all there is to finding the distance between two points.

How do you write the distance between A and B?

So, the distance between two points can be calculated by finding the length of this line segment connecting the two points. For example, if A and B are two points and if ¯¯¯¯¯¯¯¯AB=10 A B ¯ = 10 cm, it means that the distance between A and B is 10 cm.


You can do it with pythagoras theorem

If you have two points (x1, y1) and (x2, y2) then you can calculate the difference in x and difference in y, lets call them a and b.

enter image description here

var a = x1 - x2;
var b = y1 - y2;

var c = Math.sqrt( a*a + b*b );

// c is the distance

Note that Math.hypot is part of the ES2015 standard. There's also a good polyfill on the MDN doc for this feature.

So getting the distance becomes as easy as Math.hypot(x2-x1, y2-y1).


http://en.wikipedia.org/wiki/Euclidean_distance

If you have the coordinates, use the formula to calculate the distance:

var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );

If your platform supports the ** operator, you can instead use that:

const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);

To find the distance between 2 points, you need to find the length of the hypotenuse in a right angle triangle with a width and height equal to the vertical and horizontal distance:

Math.hypot(endX - startX, endY - startY)

The distance between two coordinates x and y! x1 and y1 is the first point/position, x2 and y2 is the second point/position!

function diff (num1, num2) {
  if (num1 > num2) {
    return (num1 - num2);
  } else {
    return (num2 - num1);
  }
};

function dist (x1, y1, x2, y2) {
  var deltaX = diff(x1, x2);
  var deltaY = diff(y1, y2);
  var dist = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
  return (dist);
};