HTML and CSS Reference
In-Depth Information
B = acos((a
2
+ c
2
- b
2
) / (2
×
a
×
c))
Converting these equations to JavaScript gives you this:
var B = Math.acos((a * a + c * c - b * b) / (2 * a * c)),
C = Math.acos((a * a + b * b - c * c) / (2 * a * b));
Now you have
almost
everything you need to position things. Almost, because the angles
B
and
C
aren't
really the angles of rotation you use for the segments. Look at the next diagram in Figure 14-8.
Base
D
B
c
A
Free end
a
C
b
Figure 14-8.
Figuring the rotation of side a
Although you know angle
B
, you still need to determine how much to actually rotate side
a
(
segment1
).
This is how far from zero, or horizontal, it's going to be, and is represented by angles
D
plus
B
. To get
angle
D
, call
Math.atan2
using the difference between the free end and base position. For the rotation of
side
b
(
segment0
), you know angle
C
, but that is only in relation to side
a
So you take the rotation of side
a
, plus 180, plus angle
C
, (as shown in Figure 14-9), and this is your angle
E
.
Base
c
B
a
A
Free end
+C
b
+180
degrees
Angle of
segment1
Figure 14-9.
Figuring out angle E and the rotation of side b
Yes, this way requires a lot more math. But let's see how this looks in code, which should hopefully make the
calculations a little clearer.
Programming the Law of Cosines
First, here's the complete code listing for next example (
08-cosines-1.html
), then we'll step throught it: