HTML5 Canvas [91]
var easeValue = .05;
Next, we create our two points. The first point, p1, is close to the middle of the canvas on the y-axis, and just above the top (-20) on the x-axis. The final point, p2, is in the same place on the x-axis, but near the bottom of the canvas (470) on the y-axis:
var p1 = {x:240,y:-20};
var p2 = {x:240,y:470};
Finally, we create a dynamic object for the ship that holds these values:
var ship = {x:p1.x, y:p1.y, endx: p2.x, endy:p2.y, velocityx:0, velocityy:0};
In drawScreen(), on every frame, we first find out the distance between the ship and the endpoint by subtracting the current x and y values for the ship from the endpoint x and y values. The distance will get shorter on each call to drawScreen() as the ship moves farther away from p1 and gets closer to p2. We do this for both x and y even though, in our example, only the y value will change as the spaceship gets closer to p2:
var dx = ship.endx - ship.x;
var dy = ship.endy - ship.y;
Once we have the distances, we multiply those values by easeValue to get the x and y velocities for the ship on this call to drawScreen():
ship.velocityx = dx * easeValue;
ship.velocityy = dy * easeValue;
Finally, we apply those values and draw the spaceship to the canvas:
ship.x += ship.velocityx;
ship.y += ship.velocityy;
context.drawImage(shipImage,ship.x,ship.y);
You can test this example by executing CH5EX18.html from the code distribution in your web browser, or by typing in the full code listing shown in Example 5-18.
Example 5-18. Easing out (landing the ship)
NOTE
We are showing the points in this example but because the background is black, we load in a white bitmap point image named pointwhite.png instead of the all-black image, point.png.
Easing In (Taking Off)
Easing in is the opposite of easing out. When an animation eases in, it starts slowly and then gets faster and faster. If you have ever seen a video of a space shuttle taking off, you will understand this much better. The thrust builds up as the craft moves slowly, and then gets faster and faster as it moves through the sky. We are going to use this “taking off” example as a way to develop code for an easing-in animation on HTML5