Moving Between Two Points: The Distance of a Line

Movement based on constant changes to the x or y position of an object works well for some applications, but at other times you will need to be more precise. One such instance is when you need to move an object from point A to point B at a constant rate of speed.

In mathematics, a common way to find the length of an unknown oline is to use the Pythagorean theorem:

A2 + B2 = C2

In this equation, C is the unknown side of a triangle when A and B are already known. However, we need to translate this equation into something that we can use with the points and pixels we have available on the canvas.

This is a good example of using a mathematical equation in your application. In this case, we want to find the distance of a line, given two points. In English, this equation reads like this:

The distance equals the square root of the square of the difference between the x value of the second point minus the x value of the first point, plus the square of the difference between the y value of the second point minus the y value of the first point.

You can see this in Figure 5-1. It’s much easier to understand in this format.

Distance equation

Figure 5-1. Distance equation

In the second example, we need to create some new variables in the canvasApp() function. We will still use a speed variable, just like in the first example, but this time we set it to 5, which means it ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.