HTML5 – Introduction to Canvas and Javascript

Introduction

This article is focused at developers who already know what the HTML5 canvas tag is all about, but would like to learn how to use it. Some familiarity with Javascript will assist, but I’ll explain everything from basic principles so that, should you be started with no prior knowledge on the topic, you should be able to follow along with no difficulty.

We’ll start off with a look at how the canvas element is declared within your HTML document, and how we can interact with it. Generally you would use jQueryĀ to assist you in projects like this (as the convenience it offers when dealing with potentially many different browsers is hard to ignore), but as we’re beginning from first principles here we’ll use only pure HTML5 and Javascript.

Finally we’ll examine the some of tools that you have at your disposal when using the canvas tag and put together a scene of some sort. Follow the tutorial trail and we’ll push on to complex objects and animation.

The <canvas> tag

The canvas tag can be inserted anywhere in your document where you would like the ability to generate graphics. When you create the canvas tag you’ll commonly provide both an ID for it as well as a width and a height. The ID will be used later when we retrieve the canvas tag to draw on it and the width and height specify the available drawing surface. The definition for this tag is as follows:

As previously mentioned, this tag can be inserted anywhere that you wish to have dynamic graphics. You can insert more than one of them if so desired, but make sure to update the ID so that you can retrieve the additional canvases. Let’s create the most basic possible canvas example that we can (markup wise), in order to prevent any confusion between the canvas and other elements in the page. Our incredibly basic example starts off as so –

Here we’ve created a basic HTML page, with only one element that is an 800×600 canvas. Were you to open the page, all that would be displayed would be a white screen. We have the default white background and we haven’t yet drawn anything on our canvas, so there’s nothing to see here. Let’s correct that by including a spot of Javascript.

Javascript

Javascript (JS) is a programming language designed for, and most commonly used on, websites. It is what is known as an interpretedĀ language, meaning that it can be run directly in the browser without requiring any intermediate steps. These intermediate steps are more commonly required inĀ compiledĀ languages where the language that the program is written in needs to be converted to another format before the computer can understand it.

Javascript can be embedded directly into web sites, but you’ll find it’s easier to read and maintain the code if you separate it into another file. Javascript files can be created in the same editor that you would edit a normal .html file, except the Javascript files have the extension .js.

I’m going to add a Javascript file calledĀ canvasFlash.jsĀ to this project, by creating a file with that name and adding the following lines to our website, above the <body> tag:

Javascript source files are commonly included in the header like this to ensure that they are loaded before the other elements of the page. The other change we’ll make to the HTML is to call some Javascript code (that we’ll write shortly) from the body tag’s onload method. From this point on (hopefully) we’ll be making changes purely in the Javascript. The complete HTML code, including the body tag’s onload method, is as follows.

If you were to load this page in a browser, as you may suspect, you would still be greeted with a blank white page. We haven’t written any code to take advantage of the canvas element, so nothing is rendered. However, if you open the developer toolkit of your browser (Ctrl+Shift+I in Chrome), you would most likely see message notifying you of something along the lines of “Uncaught ReferenceError: init is not defined”.

This is perfectly reasonable – we haven’t defined anything named init, although we are calling it in the onload function. Let’s correct that.

Javascript Functions

Although you could conceivably write all of your code directly into your .js file (which would cause it to be run immediately as the file was opened), this approach brings with it a multitude of issues. For one, as we include our Javascript file in the head element of the page the elements with which you wish to work are not yet loaded by the time the Javascript is run. Having all of the code in one huge group also makes it impossible to reuse code, and doesn’t allow for functions to be associated with events like text inputs or button clicks, for example.

For these reasons, we will now create the init function that we call in the body method. The basic structure of this init function is as follows:

From now on, if we callĀ  init();Ā from anywhere in our code the contents of this function will be executed. Functions can contain any standard lines of Javascript, including calls to other functions. The only line contained in our function at the moment is a comment. Comments are always preceded by a double slash – anything written after the double slash will not be executed as part of the program.

Let’s get a hold on our canvas element. The line to do this is

This line does several things – first off, it creates a variable (using “var”) namedĀ canvas. Variables store information for later use – we can store anything we may need in them, from the name of the user (once they’ve entered it), to the size of a block – anything that we will need to refer to later on.

Next, the line has the equals sign (“=”). When used like this, this sign means to assign the value of whatever is on the right hand of the sign to whatever is on the left hand side of the sign – our variable named canvas in this case.

Finally, we call another function named getElementById. This function is a standard function provided as a part of the Javascript Document Object Model (DOM)Ā and it allows us to retrieve an element from the page if given its ID. As you can see, we have another word before the function call –Ā  documentĀ lets the Javascript engine know that we’re using a function provided by the DOM. We’ll go more into functions provided to us a little later.

The result of all of this is that we now have a variable named canvas which we can use to access our canvas HTML element. Next up, we need to extract the actual canvas object from the canvas HTML element – this object will let us draw onto our canvas.

In a similar way to the manner in which we calledĀ  getElementByIdĀ from the documentĀ  object, we will now call theĀ  getContextĀ method on our canvas variable. This method takes in one parameter in which we specify the type of canvas we would like to retrieve. The only currently supported Canvas is the 2D canvas, but no doubt this will change as the spec is further developed. Our next line is:

Like the previous line, this line creates a variable named context, then assigns it the returned value of canvas.getContext('2d'). In the end, we have a reference to the 2D context which we will use to begin our actual drawing process.

Let’s make some magic!

Okay, the time has come – let’s draw something! To draw our thing, we need to decide on two other things – what it is and what colour it’ll be. Let’s start off with a nice blue rectangle. Baby steps, right?

First off, we need to set the colour of the square. This is done by calling a function on the contextĀ variable that we have (which as you recall contains the 2D context corresponding to our canvas element). Although the previous calls we’d made were to create a variable and assign it a value, in this call we’re calling a function to set a color. Because of this we do not need any return value so we do not create a variable for one or assign it using =. The line is:

Finally, we need to draw our rectangle. This is done using the drawRect function that takes a couple of inputs – the coordinate of the top left corner as well as the width and height of our rectangle. Let’s draw a rectangle starting at (15, 20) (that’s 15 pixels right, 20 pixels down) that is sized 150 by 200 pixels:

If you open this page in an HTML5 compatible browser, you should see a blue rectangle drawn on the screen. Congratulations! If you do not then you’ll need to go back over the code and check for any errors you’ve made – mis-typed words, or unclosed brackets. The developer’s toolkit from your browser should be able to assist in this.

Blue Rectangle

Victory!

Tagged with: , , , ,
Posted in Javascript

Leave a Reply