HTML and CSS Reference
In-Depth Information
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = mouse.x - arrow.x,
dy = mouse.y - arrow.y;
arrow.rotation = Math.atan2(dy, dx); //radians
arrow.draw(context);
}());
};
</script>
</body>
</html>
Make sure that you have the arrow.js file in the same directory as the 01-rotate-to-mouse.html file
and run this example in your favorite HTML5 capable web browser. If everything is set up correctly, move
your mouse around the canvas element and the arrow should follow it!
Now, suppose that you don't have Math.atan2 . You can get the ratio of opposite to adjacent angle by
dividing dy by dx and pass that in to Math.atan . Just change the Math.atan2 line in the preceding code
to use Math.atan instead, as follows:
var radians = Math.atan(dy / dx);
Try that one out, and you see the problem quickly. If the mouse is to the left of the arrow, the arrow will not
point to it, but directly away from it. Can you figure out what is going on? Going back to the diagram
showing triangles A, B, C, and D (Figure 3-13), remember that triangles A and C share the same ratio, as
well as triangles B and D. There is no way for our JavaScript code to know which angle you are referring
to, so it returns A or B. So, if your mouse is in the D quadrant, we get the angle for the B quadrant and
rotate the mouse into that area.
You can now see the benefits of Math.atan2 , and you will use it many times throughout the topic.
Waves
Let's see some more concrete uses of trigonometry with the canvas element. You've probably heard the
term sine wave before, and you've probably seen the shape shown in Figure 3-17, which is a graphical
representation of a sine wave.
 
Search WWH ::




Custom Search