The script for the game is quite long, so we'll look at it in different sections, starting with the initial structure of the script. The following code should go into the anonymous function at the bottom of the page:
var canvas = document.getElementById("c"), context = canvas.getContext("2d"), motionInt = null, dirCounter = 0, alienSpeed = 1000, aliens = [], alienMotion = function(dir) { }, addAliens = function() { }, ship = new Image(), shipPos = [430, 600]; ship.src = "img/ship.png"; ship.onload = function() { context.drawImage(ship, shipPos[0], shipPos[1]); addAliens(); };
Essentially, all we've done here is define a series of variables and an onload
event handler. The canvas
and context
variables are defined first, as in previous examples, in order to access and manipulate the canvas.
We also set a variable called motionInt
, which will be used to hold the ID of a setInterval...