HTML and CSS Reference
In-Depth Information
Drawing on Canvas
This initial tutorial doesn't use any of the vector-based drawing routines, but for the sake of getting something
up on the screen quickly, you can draw a rectangle on the page. Modify the
startGame()
method of your
game.js
file to read as follows:
function startGame() {
ctx.fillStyle = "#FFFF00";
ctx.fillRect(50,100,380,400);
}
To draw a filled rectangle, you use the
fillRect
method on the
ctx
object, but first you need to set a
fill style. You can pass in standard CSS color representations as strings to
fillStyle
, including hexadecimal
colors, RGB triples, or RGBA quads.
To layer a semitransparent rectangle on top of the existing one, add the following:
function startGame() {
ctx.fillStyle = "#FFFF00";
ctx.fillRect(50,100,380,400);
// Second, semi-transparent blue rectangle
ctx.fillStyle = "rgba(0,0,128,0.5);";
ctx.fillRect(0,50,380,400);
}
If you add the preceding code and reload your
index.html
file, you see a nice, big blue rectangle smack
dab in the middle of your black canvas.
Drawing Images
Alien Invasion
is an old-school, top-down 2-D shooter game with retro-looking bitmap graphics. Luckily canvas
provides an easy method called
drawImage
that comes in a couple of flavors, depending upon whether you
want to draw an entire image or just a portion of an image.
The only complication is that, to draw those graphics, the game needs to load the image first. This isn't a
huge deal because browsers are handy at loading images; however, they load them asynchronously, so you need
to wait for a callback to let you know that the image is ready to go.
Make sure you have copied the
sprites.png
file over from the topic assets for Chapter 1 into an
im-
ages/
directory underneath your current game, and then add the code from
Listing 1-4
to the bottom of your
startGame
function.
Listing 1-4:
Drawing images with canvas (canvas/game.js)
function startGame() {
ctx.fillStyle = "#FFFF00";
ctx.fillRect(50,100,380,400);
// Second, semi-transparent blue rectangle
ctx.fillStyle = "rgba(0,0,128,0.8);";
ctx.fillRect(25,50,380,400);
var img = new Image();