2D HTML5 Game Tutorial
Set-up an HTML5 canvas
What is an HTML5 canvas?
- When you want to draw your own image, animation or game with HTML5, you're going to need a
<canvas>
. It's a container for graphics and you can draw on it by using JavaScript. You can draw shapes and paths, but also text and images. - It basically works like an
<img>
tag, only you can draw the image yourself instead of loading it from an external source. In fact, in most modern browsers, you can even right click a canvas element and save the image that is currently being displayed. It's like a dynamic image. - The canvas will be the core of all the drawing operations for your game. It works like a drawing board, you can draw on it and clear it. But unlike drawing in real life, drawing on the canvas takes hardly any time. You can repeat the process of drawing and clearing so quickly that, if you would change the position of objects just a little bit each time before you draw, you'll get the perception of motion. This is the basic principle of animations and games. You clear the previous frame and draw the next with updated positions for all your objects, for hundreds of times in a row.
- In this tutorial you'll start of easy and learn about drawing a single static image to the canvas
Set-up a basic HTML5 file
Before you can draw any kind of graphics, you'll have to set-up a basic HTML5 file. You'll have to tell the browser how to interpret the file and what kind of content it contains. Let's get started with the code below:
<body>
<!--Your canvas will come here -->
</body>
<script>
// Your script will come here
</script>
Let's take a closer look:
- Inside the
<body>
tag is where all the actual content of the page will be stored. This is also where your canvas will be placed. - You can see two
<script>
tags right before the end of the<body>
tags. Between those tags is where your program is going to start.
You can copy this code and store it in a file named index.html. This file can be run by any browser and will display your newly created HTML5 web page.
Create a canvas element
Now directly after the <body>
tags, add a <canvas>
element. This is the place where the graphics of your game will be drawn later on.
<canvas id="canvas" width="750" height="400" style="border:1px solid lightgrey;">
Your browser does not support the HTML5 canvas tag.
</canvas>
Get a reference to the canvas
To perform drawing operations, you'll need a decent reference in your code to your canvas. Expand the script
tags with the following JavaScript code:
<script>
"use strict";
let canvas;
let context;
window.onload = init;
function init(){
// Get a reference to the canvas
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
draw();
}
</script>
The most important steps are taken inside the init() function. In there the canvas is stored for later reference by calling getElementById() to retrieve the canvas element.
The canvas has no functions to draw on its own, you'll need a context for that. Call getContext() to retrieve the context from the canvas. '2d' is passed as argument to get a CanvasRenderingContext2D object. That's the context you need to draw 2D objects. There are also other context types like WebGL, for 3D, but that's not what we need right now.
Once the references are made, the function draw() is called. In there, the actual drawing operation will be performed.
JavaScript in strict mode
"use strict"
is telling the browser to run the code in strict mode. This means your code will be validated more strictly. Things like using an undeclared variable are no longer allowed. This will force you to write cleaner code, which will prevent coding errors. It is an optional line, but it is recommended to leave it in. Learn more about use strict here.
How to make sure the element is loaded?
If you don't wait for the page to load before referencing the canvas, you're trying to work with a canvas that isn't there. This will result in an error saying there is no canvas element.
To fix this you can use the onload
event. The window.onload event will trigger once the whole page is loaded. This will make sure all elements and resources on the page are available before you execute your code. The init() function is set as the event handler. Once the onload event fires, init() will be called and the canvas will be available for referencing.
Draw your first graphics
The last piece of the puzzle is the draw() function. The function looks like this:
function draw() {
// Get a random color, red or blue
let randomColor = Math.random() > 0.5? '#ff8080' : '#0099b0';
// Draw a rectangle
context.fillStyle = randomColor;
context.fillRect(100, 50, 200, 175);
}
A fillStyle
is set on the context and a rectangle is draw by calling fillRect()
.
Open your .html file and it should draw a rectangle on the canvas:
With the current code, the rectangle is either red or blue. This is because every time the page is loaded a new random color is picked in the
draw()
function, by using Math.random()
to pick a color as fill style. You can try to refresh this page a couple of times and see the color getting changed.