Flash Tutorial Links:
Play Games: HTML5 Tutorials:

How To Write Text Onto Your HTML5 Canvas

Journey to a completed game begins with a single first step. That first step here in writing HTML5 games is to write text to the game canvas.

Foreword

The tutorials here in general make a basic assumption that you are not a total newbie to programming or basic html. The walkthrough of the codes will zoom in and highlight areas that are crucial to creating the game, but expects some basic understanding of html as well as how to code in Javascript.

Also, in the name of clarity and ease of explanation, optimization of codes is not done.

Getting Started

We will be using a very basic html here with a game canvas object. It links to the javascript file called game.js which will contain some codes to write onto the canvas. It also links to the javascript file constants.js which will contain some static values to initialise the game. For completeness sake, this is how the html file looks like.

edited html

If you have gone through the earlier Set Up tutorial, you'll realise that it is the same. In fact, for subsequent tutorials, we will not be making much modifications to this html file.

Step 1 - Specify the fonts

Let's zoom into the constants.js file. You will notice on line 7 that we are specifying a value of "bold 20px sans-serif". Later, you will see us assigning this value to act as the default font when we write to the canvas.

//------------
//System Values
//------------
var STAGE_WIDTH = 600,
	STAGE_HEIGHT = 400,
    TIME_PER_FRAME = 33, //this equates to 30 fps
    GAME_FONTS = "bold 20px sans-serif";
	
var COUNTER_X = 100,
	COUNTER_Y = 100;

In the game.js file, the codes below show how we assign that default font to the canvas.

//------------
//System Vars
//------------
var stage = document.getElementById("gameCanvas");
stage.width = STAGE_WIDTH;
stage.height = STAGE_HEIGHT;
var ctx = stage.getContext("2d");
ctx.fillStyle = "black";
ctx.font = GAME_FONTS;

Line 4 shows how we get the canvas object from the html file and assign it to the variable stage. Lines 5 and 6 set the height and width of the game canvas. Line 7 gets the 2D context of the canvas, which is actually an object that contains the properties and methods for drawing onto the canvas. We store that reference in the variable ctx. Line 8 tells the computer what style you will use when calling subsequent methods such as fillRect, etc. Over here, we simply tell it that the default fillStyle will be black colour.

Line 9 is where we set the default text font.

Step 2 - Write the text

Look at the example below.

//------------
//Game Loop
//------------
function update()
{	
	counter++;
	
	//Draw Timer
	ctx.fillStyle = "white";
	ctx.fillText("Time is: "+counter, COUNTER_X, COUNTER_Y);
}

As the game loop executes 30 times a second, we increase the counter (so that we can see changes on the screen), and sets the fillStyle to white. Line 23 then shows you the exact code to use to write text onto the screen. 3 parameters are passed in. The 1st parameter is the text you want to write; in this case, it is "Time is: "+counter. This effectively writes the words "Time is: 1", followed by "Time is: 2", followed by "Time is: 3", ... and you get the drift.

The 2nd parameter specifies the x coordinate where the text will be written, and the 3rd parameter specifies the y coordinate.

However, you can see from the end result that things have gone haywire.

fill text wrong results

The area where the numbers should have been looks messed up. To delve deeper into what happened, let's vary the x and y coordinates.

By varying the codes a little ... we basically increase the y position of the written text by 20 pixels down each time.

//------------
//Game Loop
//------------
function update()
{	
	counter++;
	
	//Draw Timer
	ctx.fillStyle = "white";
	ctx.fillText("Time is: "+counter, COUNTER_X, COUNTER_Y+counter*20);
}

The end result looks like this.

fill text wrong 2 results

With this, the earlier query of why the number area was messed up, becomes clear. We have been writing the text one on top of the other!

Step 3 - Clear the entire game stage first before writing

Solving this problem is simple. Each time, before we write to the game canvas, we draw a rectangle over the canvas, effectively wiping it clean of any text or graphics. To do that, we use another method called fillRect.

//------------
//Game Loop
//------------
function update()
{	
	counter++;
	
	//Clear Canvas
	ctx.fillStyle = "black";
	ctx.fillRect(0, 0, stage.width, stage.height);	
		
	//Draw Timer
	ctx.fillStyle = "white";
	ctx.fillText("Time is: "+counter, COUNTER_X, COUNTER_Y);
}

Line 22 resets the fillStyle back to the original background colour, in this case, black. Then line 23 calls the fillRect function, taking in 4 parameters. 1st and 2nd parameters specify the x and y position respectively to start drawing the rectangle at, and the 3rd and 4th parameters specify the width and height of this rectangle that you are going to draw respectively.

The end result, is perfect now. You should see the timer counter run endlessly.

fill text correct results

Until Next Time

This simple tutorial explains the bare minimum codes you need to write to get some text out to the players. There are many more methods and properties you can make use of in drawing text or rectangles, such as varying the gradient of the rectangle. For that, you can head over to w3schools for more detailed explanations on the other methods.

Downloads

You can view the demo of this tutorial here (opens in new window).

You can download the files used in this tutorial here.



Flash Resources
Preloader FPS Display Sounds & Music
Keycodes Name Generator

Game Development Resources
Sprite Sheets


Flash Tutorial Links:
Play Games: HTML5 Tutorials:
gaming tools download on app store now!
Home | About Us | Contact Us
Powered by Make Flash Games. All Rights Reserved.
By Joseph Tan