HTML and CSS Reference
In-Depth Information
Figure 7-10. Determining the point on a circle using trigonometric functions
In
Figure 7-10
,
the angle, theta, needs to be in radians, which equals the angle in de-
grees times pi divided by 180. Translated into code, the formula in
Figure 7-10
might
look like this:
x = 50 + Math.cos( 45 * Math.PI / 180 ) * 20;
y = 50 + Math.sin( 45 * Math.PI / 180 ) * 20;
This would find the x and y coordinates of a point that was at a 45-degree angle and
was 20 pixels out from another point at the x, y coordinate of 50, 50 on the canvas.
Let's look at a full example. This example draws a spiral on the canvas, the result of
which is shown in
Figure 7-11
. It runs a loop a number of times that increases the
distance from the center ("c" in
Figure 7-10
)
and increases the angle in degrees:
// declare the global variables
var canvas;
var context;
var centerX;
var centerY;
var degrees = 0;
var radius = 1;
function init() {
canvas = document.getElementById( "canvas" );
Search WWH ::
Custom Search