HTML and CSS Reference
In-Depth Information
Next we create our two points. The first point, p1 , is close to the middle of the canvas on the
x-axis, and just above the top ( −20 ) on the y-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
var p1 = { x : 240 , y :- 20 };
var
var p2 = { x : 240 , y : 470 };
Finally, we create a dynamic object for the ship that holds these values:
var
var ship = { x : p1 . x , y : p1 . y , endx : p2 . x , endy : p2 . y , velocityx : 0 , velocityy : 0 };
In drawScreen() ,oneveryframe,wefirstfindoutthedistancebetweentheshipandtheend-
point 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
var dx = ship . endx - ship . x ;
var
var dy = ship . endy - ship . y ;
When we have the distances, we multiply those values by easeValue to get the x and y velo-
cities 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 );
Youcantestthisexamplebyexecuting CH5EX18.html fromthecodedistributioninyourweb
browser, or by typing in the full code listing shown in Example 5-18 .
Example 5-18. Easing out (landing the ship)
<!doctype html>
<html
<html lang= "en" >
<head>
<head>
<meta
<meta charset= "UTF-8" >
<title>
<title> CH5EX18: Easing Out (Landing The Ship) </title>
</title>
< script src = "modernizr.js" >< /script>
< script type = "text/javascript" >
window . addEventListener ( 'load' , eventWindowLoaded , false
false );
var
var shipImage ;
function
function eventWindowLoaded () {
Search WWH ::




Custom Search