HTML and CSS Reference
In-Depth Information
Drawing Text on Canvas
Drawing text on the canvas is straightforward and allows you to use any font loaded on the page. This flexibility
means you can use any of the standard web-safe fonts as well as any fonts that have been loaded via @font-
face onto the page.
The declarations for @font-face take some care because depending on the browsers that need to be sup-
ported, four different file formats need to be available. Luckily, if you aren't going to install the files locally, but
rather serve them off an online service such as the free Google web fonts, all that's needed is a single linked style
sheet. (You can browse the fonts available for free use at Google web fonts at ( www.google.com/webfonts .)
For Alien Invasion , the font Bangers gives the game a nice retro “Invasion of the Body Snatchers” feel. Add
the following line to your HTML (not your JavaScript) below the base.css link tag:
<head>
<meta charset="UTF-8"/>
<title>Alien Invasion</title>
<link rel="stylesheet" href="base.css" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Bangers'
rel='stylesheet' type='text/css'>
</head>
Next, the game needs a TitleScreen class to display some text centered on the screen. To do this you
must use a new canvas method that hasn't been discussed yet, fillText , and two new canvas properties,
font and textAlign .
The current font used is set by passing a CSS style to context.font , for example:
ctx.font = "bold 25px Arial";
This declaration would set the current font used by both measureText and fillText to 25 pixels high,
make it bold, and use the Arial font family.
To make sure the text is centered on a specific location horizontally, you'll need to set the con-
text.textAlign property to center.
ctx.textAlign = "center";
After you calculate the location for the text and set the font style appropriately, you can use fillText to
draw solid text onto the canvas:
fillText(string, x, y);
fillText takes the string to draw and an x and y location for the top-left corner.
Armed with these text-drawing methods, you now have the tools to draw a title screen that shows a title and
a subtitle and calls an optional callback when the user presses the fire key.
Listing 1-8 shows the code to get that done. Add the TitleScreen class to the bottom of your en-
gine.js file.
Listing 1-8: The TitleScreen (titlescreen/engine.js)
var TitleScreen = function TitleScreen(title,subtitle,callback) {
this.step = function(dt) {
if(Game.keys['fire'] && callback) callback();
};
this.draw = function(ctx) {
 
 
Search WWH ::




Custom Search