HTML and CSS Reference
In-Depth Information
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:
A 2 + B 2 = C 2
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.
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 will move 5 pixels on every call to drawScreen() :
var
var speed = 5 ;
We then create a couple of dynamic objects—each with an x and a y property—that will rep-
resent the two points we want to move between. For this example, we will move our circle
from 20 , 250 to 480 , 250 :
var
var p1 = { x : 20 , y : 250 };
var
var p2 = { x : 480 , y : 250 };
Nowitistimetore-create thedistance equationin Figure 5-1 .Thefirststepistocalculate the
differences between the second and first x and y points:
Search WWH ::

Custom Search