HTML and CSS Reference

In-Depth Information

You have seen the code to create an effect like this already. In the
canvasApp()
function,

we would create the starting variables like this:

var speed = 4;

var angle = 305;

var radians = angle * Math.PI/ 180;

var radius = 15;

var vx = Math.cos(radians) * speed;

var vy = Math.sin(radians) * speed;

Next, we create the starting point for the ball as
p1
, and then create a dynamic object

that holds all the values we created for the
ball
object:

var p1 = {x:20,y:theCanvas.width-radius};

var ball = {x:p1.x, y:p1.y, velocityx: vx, velocityy:vy, radius:radius};

If we want to add gravity to the application, we would first create a new variable named

gravity
and set it to a constant value of
.1
:

var gravity = .1;

Next, in the
drawScreen()
function, we apply this gravity value to the
ball
object when

it is drawn to the canvas (
ball.velocityy += gravity
). We want the ball to stop moving

when it hits the “ground” (the bottom of the canvas), so we test to see whether the
y

position of the
ball
plus the
radius
of the ball (the outer edge) has passed the bottom

of the canvas (
ball.y + ball.radius <= theCanvas.height
). If so, we stop the ball's

movement:

if (ball.y + ball.radius <= theCanvas.height) {

ball.velocityy += gravity;

} else {

ball.velocityx = 0;

ball.velocityy = 0;

ball.y = theCanvas.height - ball.radius;

}

Next, we apply the constant
x
velocity and the new
y
velocity to
ball
, and draw it to

the canvas:

ball.y += ball.velocityy;

ball.x += ball.velocityx;

context.fillStyle = "#000000";

context.beginPath();

context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);

context.closePath();

context.fill();

Figure 5-17
shows what the path looks like when simple gravity is applied to a ball

moving on a vector. We have added the points to illustrate the path.