HTML and CSS Reference
In-Depth Information
x2, y2
(58, 50)
dist
?
dy = -6
x1, y1
(50, 56)
dx = 8
Figure 3-23.
Turn it into a right-angle triangle.
Here,
dx
is the distance between the two objects on the x axis, and
dy
is the distance on the y axis. You
can now find
dx
by subtracting x1 from x2: 58 - 50 = 8. Similarly, you subtract y1 from y2 to get
dy
, which
is −6. Now, using the Pythagorean Theorem, if you square both of these and add them together, you get
the square of the distance. In other words −6
2
+ 8
2
= dist
2
. Breaking that down, you get 36 + 64, or 100 =
dist
2
. With some basic algebra, you can reduce that to
.100 = dist
. And from that, you can easily figure
out that the distance between the two objects is 10.
Let's abstract that a bit so you have a formula that you can use in any situation. Given two points, x1, y1
and x2, y2, you figure the x distance and y distance, square them, sum them, and take the square root.
Here it is in JavaScript:
var dx = x2 - x1,
dy = y2 - y1,
dist = Math.sqrt(dx * dx + dy * dy);
Pay particular attention to these lines because they make up the next big tool in your toolbox. The first two
lines get the distances on each axis. If you are interested in the distance and won't use
dx
and
dy
to
calculate any angles, it doesn't matter whether you subtract x1 from x2 or vice versa. The final result for
dist
is always positive. The last line performs three steps in one shot: It squares each of the values, adds
them, and finds the square root. For clarity, you can break down the steps into separate statements. After
you are familiar with that single line, it will be clear to you. You see it and think “Pythagorean Theorem.”
Let's try it in a real world example. The next example,
10-distance.html
, creates a couple of rectangles,
randomly positions them, and then calculates and prints the distance between them.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Distance</title>
<link rel="stylesheet" href="style.css">
</head>