02.06.2013 Views

jQuery 1.4 Animation Techniques - Index of

jQuery 1.4 Animation Techniques - Index of

jQuery 1.4 Animation Techniques - Index of

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Canvas <strong>Animation</strong>s<br />

Time for action – the initial script<br />

The script for the game is quite long so we'll look at it in different sections, starting with the<br />

initial structure <strong>of</strong> the script. The following code should go into the anonymous function at<br />

the bottom <strong>of</strong> the page:<br />

var canvas = document.getElementById("c"),<br />

context = canvas.getContext("2d"),<br />

motionInt = null,<br />

dirCounter = 0,<br />

alienSpeed = 1000,<br />

aliens = [],<br />

alienMotion = function(dir) {<br />

},<br />

};<br />

addAliens = function() {<br />

},<br />

ship = new Image(),<br />

shipPos = [430, 600];<br />

ship.src = "img/ship.png";<br />

ship.onload = function() {<br />

context.drawImage(ship, shipPos[0], shipPos[1]);<br />

addAliens();<br />

What just happened?<br />

Essentially, all we've done here is define a series <strong>of</strong> variables and an onload event handler.<br />

The canvas and context variables are defined first, as in previous examples, in order to<br />

access and manipulate the canvas.<br />

We also set a variable called motionInt which will be used to hold the ID <strong>of</strong> a<br />

setInterval() function later on, a variable called dirCounter which will be used to<br />

determine which direction the aliens move in, an alienSpeed variable to set the speed that<br />

the aliens move at, and an empty aliens array which we'll use to keep track <strong>of</strong> each alien<br />

on the page.<br />

[ 292 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!