HTML and CSS Reference
In-Depth Information
stars.height = Game.height;
var starCtx = stars.getContext("2d");
Because the stars field needs to be the same size as the game's canvas, you can set the size by pulling out the
width and height properties that were set in the Game.initialize method.
After you create the canvas, you can start drawing stars (or rectangles) onto it. The easiest way to do this is to
call fillRect once for each star that needs to be drawn. A for loop combined with using Math.random()
to generate a random x and y location gets the job done:
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);
}
The only piece that hasn't been mentioned is the globalAlpha property. This property sets the level of
opacity for the canvas element. Because there are multiple layers of stars moving at different speeds, a nice ef-
fect is to have the slower stars be slightly less bright than the faster moving ones to simulate their being farther
away.
Next is the draw method. The Starfield needs to draw the entire canvas element containing the stars
onto the game's canvas; however, because it will scroll constantly, it needs to be drawn twice: once for the top
half and once for the bottom half. The method uses the starfield's offset, a number between zero and the height
of the game to first draw whatever part of the starfield has been shifted off the bottom of the game back at the
top, and then draws the bottom part.
this.draw = function(ctx) {
var intOffset = Math.floor(offset);
var remaining = stars.height - intOffset;
if(intOffset > 0) {
ctx.drawImage(stars,
0, remaining,
stars.width, intOffset,
0, 0,
stars.width, intOffset);
}
if(remaining > 0) {
ctx.drawImage(stars,
0, 0,
stars.width, remaining,
0, intOffset,
stars.width, remaining);
}
}
Search WWH ::




Custom Search