Measuring the length of a line

We now have the ability to choose a point, and to draw a circle around that point. We also have the ability to draw a straight line from one point to another, but we’re still missing some features of these basic tools.

Namely, the ability to adjust the compass to the distance between two points.

As we’re using an (x, y) grid, we can use all sorts of well-tested equations. The “Distance Formula” is one such equation. As it’s name implies, it finds the distance (between two points).

It’s also known as the Pythagorean theorem.

It goes like this:  c = \sqrt{a^2 + b^2}. \,

If you want to understand how the distance “c” is found, I recommend reading through the linked article.

Following with previous articles, we’re going to create a function that accepts two points:

function distanceBetweenTwoPoints (pointA, pointB) {
  // Also known as "the distance formula" (a^2 + b^2 = c^2)
  // Note again that we're scaling the values in order to get accurate results

  distanceXScaled = ((pointB.attr("cx") *scale) - (pointA.attr("cx") *scale));
  distanceYScaled = ((pointB.attr("cy") *scale) - (pointA.attr("cy") *scale));

  lineLengthScaled = Math.sqrt(Math.pow(distanceXScaled, 2) + Math.pow(distanceYScaled, 2));

  lineLength = Math.round(lineLengthScaled) / scale;

  return lineLength;
}

This function returns the value, such as:

pointA = new point(84, 84);
pointB = new point(168, 168);

result = distanceBetweenTwoPoints (pointA, pointB);

console.log(result); // 118.7939392393