HTML and CSS Reference
In-Depth Information
common mistake is to enter them as x, y, rather than y, x, as specified. For the example given, you
enter Math.atan2(1, 2) . Go ahead and try it out, remembering to convert to degrees:
console.log(Math.atan2(1, 2) * 180 / Math.PI);
This should give you the angle, 26.565051177078, which is correct for triangle B as shown
previously. Now, knowing that -1/ -2 (triangle D) gave us some confusion, let's try that out.
console.log(Math.atan2(-1, -2) * 180 / Math.PI);
This gives you the possibly unexpected result of -153.434948822922. What is that all about?
Perhaps the diagram in Figure 3-14 will explain.
-153.43
D
26.57
Figure 3-14. Two ways of measuring an angle
Although the inner angle of triangle D is indeed +26.57, as taken from its own bottom leg,
remember that in the canvas, angles are measured clockwise from the positive x axis. Thus, from
the canvas element's viewpoint of screen measurements, the angle you are looking at is -153.43.
How is this useful? Well, let's get to the first practical application of trigonometry using the canvas
element.
Rotation
Here is the challenge: You want to draw an object and rotate it so that it always points to the
mouse. Rotation is a useful tool to add to your toolbox, it can be used in games and interface
elements, among other things. And in fact, rotation is not just limited to the mouse. Because the
mouse coordinates are just x and y values, you can extend this technique to force an object to aim
itself at any particular point, such as another object or the center or corner of the screen.
Let's work through an example. You can follow along with the steps or just open the document 01-
rotate-to-mouse.html and arrow.js file (which you can download from the topic's page at
www.apress.com , along with all of the other code for this topic) to have all the work done for you.
First, you need something to rotate. This is an object that contains commands to draw an arrow to
a canvas element using the given canvas context. Because you will use this arrow object again,
make it into a class so each instance can have its own properties. Add the following JavaScript code
to the file arrow.js, which we import into our main HTML document:
 
Search WWH ::




Custom Search