HTML and CSS Reference
In-Depth Information
The code looks slightly confusing because it uses the nine-parameter version of drawImage to draw the
slices, but it's actually just slicing the starfield into a top half and a bottom half, and drawing the top half at the
bottom of the game canvas and the bottom half at the top of the canvas.
Listing 1-7 shows the Starfield class in its entirety, which should go into the game.js file.
Listing 1-7: The Starfield (starfield/game.js)
var Starfield = function(speed,opacity,numStars,clear) {
// Set up the offscreen canvas
var stars = document.createElement("canvas");
stars.width = Game.width;
stars.height = Game.height;
var starCtx = stars.getContext("2d");
var offset = 0;
// If the clear option is set,
// make the background black instead of transparent
if(clear) {
starCtx.fillStyle = "#000";
starCtx.fillRect(0,0,stars.width,stars.height);
}
// Now draw a bunch of random 2 pixel
// rectangles onto the offscreen canvas
starCtx.fillStyle = "#FFF";
starCtx.globalAlpha = opacity;
for(var i=0;i<numStars;i++) {
starCtx.fillRect(Math.floor(Math.random()*stars.width),
Math.floor(Math.random()*stars.height),
2,
2);
}
// This method is called every frame
// to draw the starfield onto the canvas
this.draw = function(ctx) {
var intOffset = Math.floor(offset);
var remaining = stars.height - intOffset;
// Draw the top half of the starfield
if(intOffset > 0) {
ctx.drawImage(stars,
0, remaining,
stars.width, intOffset,
0, 0,
stars.width, intOffset);
}
// Draw the bottom half of the starfield
if(remaining > 0) {
 
 
Search WWH ::




Custom Search