Prepare a blank canvas

Set-up an HTML5 canvas

Set-up an HTML5 file with a canvas. Learn how to scale the canvas and perform drawing operations. By the end of this tutorial you can draw your first graphics to the screen.

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. The <canvas> tag first arrived with the introduction of HTML5. 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.

Draw multiple frames on a canvas

In this tutorial you'll start of easy and learn about drawing a single static image to the canvas. Check out the canvas animation tutorial if you already know how to do that and want to skip to the next step straight away.

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:


                    
                        <!DOCTYPE html>
                        <html lang="en">
                            <head>
                                <meta charset="UTF-8">

                                <title>HTML5 Game</title>
                                <meta name="description" content="A basic HTML5 game">
                                <meta name="author" content="[Your name]">
                            </head>
                            <body>

                                <!--Your canvas will come here -->

                                <script>
                                    // Your script will come here
                                </script>
                            </body>
                        </html>
                    
                    

Let's take a closer look:

  • The <!DOCTYPE> declaration tells the browsers what HTML version the page is written in. The HTML5 doctype is short and simple compared to older versions.
  • The <meta> tags and the <title> tag describe the content of the page. Search engines like Google use this information to build search results.
  • 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. Too bad it is still completely empty. Let's do something about that by adding a canvas.

Add 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>
            
            

When you try to use the canvas in a browser that has no canvas support, the fallback content will be shown.

For now it's just a simple message about lacking support, but you could make something fancier. Perhaps you could add a static image of what your canvas content would've been? Just place the fallback content between the <canvas> tags.

Scaling the canvas to fit on all screen sizes

When you refresh your page, you should see the border of the canvas. The element has its width and height properties set. That's to define the size of your canvas, your drawing board. Every drawing operation will be performed in this coordinate space.

You can scale the total canvas by using standard CSS to set a width and height percentage on the element. For example, applying width: 100% to the element would stretch the canvas to fit the maximum width. But all drawing operations will still be done within the coordinate space of the canvas. You'll never have to take the actual size of your canvas into account when drawing.

How is this helpful? Well this enables you to work on a game with a set resolution of let's say 1280x720 and run this game on devices with bigger and smaller screens. While programming, an x-position of 1280 will always be the right edge of your screen even if the actual screen size of the current device is much smaller or larger than that. The scaling of the canvas takes care of it.

Canvas is stretched to fit screen size

This principle is demonstrated in the example image above. The position and size of the circle scale with the screen size, but in your code the coordinates of the circle will always be set at (800, 300).

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. You'll implement the function in a bit.

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() (If you want to know more about drawing, check out the next tutorial. It will go much deeper into the subject of drawing shapes on the canvas).

Proof it's a dynamic image

When you add the previous code to your index.html file and run the file in the browser, you will actually see something getting draw on the canvas. It's a big rectangle!

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.

The random color is used to demonstrate the fact that you are not looking at a static image. You are drawing your own graphics dynamically. You can modify the arguments inside the function to create rectangles of different sizes and colors.

What's next?

You finished this tutorial and have your own HTML5 canvas ready to use. You can perform your own drawing operations now. If you have any questions, feel free to ask them in the comments.

In the next step of this tutorial series you'll learn more about how to use the canvas to draw shapes, (SVG) paths and text. And soon after that you'll start moving objects around, making things come alive.

Leave a comment

(Login with Facebook to view the comment section)