HTML and CSS Reference
In-Depth Information
In this example, the variable angle starts out as 0 and increments by 0.1 until it's greater than Math.PI *
2 . It then prints the sine of that angle. In the list of results, you see it starts at 0, goes up to almost 1, then
down to almost -1, and back to around 0. You never reach exactly 1 or 0 because, using an increment of
0.1, you never get an exact multiple of pi or pi/2.
Smooth up and down motion
So what can you use Math.sin(angle) for? Have you ever needed to move something up and down or
back and forth smoothly? Then this is your function. Consider this: Instead of just going from 0 to 1 and -1
and back to 0, and stopping there, keep adding on to the angle. You keep getting the wave over and over
again. And instead of taking the 1 and -1, multiply those values by some higher value, say 100, and you
have a stream of values that goes from 100 to -100, back and forth, continuously.
The next example uses a new object, defined by the Ball class. You can see the file, ball.js , here:
function Ball (radius, color) {
if (radius === undefined) { radius = 40; }
if (color === undefined) { color = "#ff0000"; }
this.x = 0;
this.y = 0;
this.radius = radius;
this.rotation = 0;
this.scaleX = 1;
this.scaleY = 1;
this.color = utils.parseColor(color);
this.lineWidth = 1;
}
Ball.prototype.draw = function (context) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.rotation);
context.scale(this.scaleX, this.scaleY);
context.lineWidth = this.lineWidth;
context.fillStyle = this.color;
context.beginPath();
//x, y, radius, start_angle, end_angle, anti-clockwise
context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
context.closePath();
context.fill();
if (this.lineWidth > 0) {
context.stroke();
}
context.restore();
};
This draws a circle when it is passed a canvas context as a parameter to its draw method. When you
create the ball, you can initialize it with a radius and a color if you want. If not, it uses the default
arguments of 40 for the radius and red for the color. This class is simple, but so useful that you will see it
many times throughout the rest of the topic. So keep it handy.
 
Search WWH ::




Custom Search