Online Book Reader

Home Category

HTML5 Canvas [92]

By Root 6504 0
Canvas.

In canvasApp(), we start our code much the same way as in the last example—by creating a variable named easeValue:

var easeValue = .05;

However, for easing in, instead of this being a percentage of the remaining distance between two points, it is simply a constant value added to the velocity of the ship on each frame. Figure 5-22 shows what this would look like. We have added the points again to illustrate how the animation speeds up as the ship takes off.

Figure 5-22. Ship taking off (easing in)

First, we set the beginning position of the ship (p1) to the bottom center of the canvas. Then, we set the beginning speed of the ship very low (.5 pixels per frame), and set the angle to 270 (straight up the canvas). We then calculate the x and y velocity values for the ship:

var p1 = {x:240,y:470};

var tempSpeed = .5;

var tempAngle = 270 ;

var tempRadians = tempAngle * Math.PI/ 180;

var tempvelocityx = Math.cos(tempRadians) * tempSpeed;

var tempvelocityy = Math.sin(tempRadians) * tempSpeed;

var ship = {x:p1.x, y:p1.y, velocityx:tempvelocityx, velocityy:tempvelocityy};

In drawScreen(), instead of finding the distance between two points, we add the easeValue to the x and y velocities on each frame, and then apply it to the ship x and y values before drawing it to the canvas. This creates a linear increase in speed, resulting in the easing-in effect we want to see:

ship.velocityx = ship.velocityx + ( ship.velocityx*easeValue);

ship.velocityy = ship.velocityy + ( ship.velocityy*easeValue);

ship.x += ship.velocityx;

ship.y += ship.velocityy;

context.drawImage(shipImage,ship.x,ship.y);

You can see this example by executing CH5EX19.html from the code distribution, or by typing in the code listing shown in Example 5-19.

Example 5-19. Easing in (taking off)

CH5EX19: Taking Off (Fake Ease In)

Your browser does not support HTML5 Canvas.

NOTE

For more information on easing, check out Robert Penner’s easing equations: http://www.robertpenner.com/easing/. These equations have been implemented in jQuery for JavaScript at http://plugins.jquery.com/files/jquery.animation.easing.js.txt.

Return Main Page Previous Page Next Page

®Online Book Reader