Codular

HomeWriters RSS

Beginner's Guide to HTML5 Canvas

Introduction

HTML5 canvas is very powerful, and has been used by many people to make lots of really interesting things. Whether that's creating a fly-through of Minecraft or porting Doom to the browser.

While canvas can be used for some seriously powerful things, it can also be used for very basic things using the powerful JavaScript APIs that have been made available. Here we'll cover working in the 2D context, and using many of the basic functionality that exists.

The Canvas

The canvas is very simple, it's an element that just requires a width and height attribute assigned to it at the least - and most probably an id so that you can refer to it in the JS.

We'll be using the below canvas element in all of the examples:

<canvas width='200' height='200' id='canvas'></canvas>

Context is key

Also, in all of the examples that we use, we'll be referring to the 2D context of the canvas - we can get this using the getContext() method which takes a parameter stating which context you want to use. In our case we'll be passing it the parameter of '2d', and assigning it to a variable that we'll use throughout:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

We now have the basis for all of the examples that we'll be using throughout this article.

Browser Support

There are some browsers out there being used that don't support canvas yet - and as such you will want to make sure you can determine if the user has support, or send them a message if they don't.

By defualt, any text that you put within the canvas tags will be shown if the browser doesn't support canvas elements, and will not be shown if it does have support:

<canvas width='200' height='200' id='canvas'>Your browser does not support canvas - go get Chrome!</canvas>

But what about the JavaScript code? The way that this article is written assumes that they have support for canvas - but you will want to only run your code if the support is definite, we can use a simple conditional:

var canvas = document.getElementById('canvas');
if(canvas.getContext){
    var context = canvas.getContext('2d');
    // Other code here
}

Drawing Lines

We need to do this in 4 stages:

Prepare to draw

This is as simple as using the beginPath() method within the context that we had previously established:

context.beginPath();

Move to the line start

Always using the methods with in the context, here we call moveTo(), this takes two parameters - with the first being the x co-ordinate and the second being the y co-ordinate.

context.moveTo(25, 15);

Draw invisible

This takes two parameters the same as the previous method, here we call lineTo():

context.lineTo(100, 100);

Stroke the line

Finally, we need to make the line visible - by default the stroke() method uses black, however we can change that by assigning a new value to the strokeStyle variable.

Firstly to stroke:

context.stroke();

Changing the colour to blue:

context.strokeStyle = '#0000ff';

If changing the colour, it should be called before you stroke the line/shape.

Example Code

<canvas width='200' height='200' id='canvas'></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.moveTo(25, 15);
    context.lineTo(100, 100);
    context.strokeStyle = '#0000ff';
    context.stroke();
</script>

Drawing Circles

Just as easy as drawing a line, there are two different ways you can draw a circle - but both revolve around the same method - arc() - which takes 6 parameters:

  1. x co-ordinate
  2. y co-ordinate
  3. Radius of the circle
  4. Starting angle in radians.
  5. Ending angle in radians.
  6. Whether the path is drawn anti-clockwise or not.

When using an arc, much like the lineTo() method - it simply draws a path that we can later use. We can either stroke() it so that we end up with a simple line around the circle (or section of a circle), or we can fill it to get a completely solid circle.

Both methods have the same starting code which is to specify that we're starting a path and then to specify the arc. Let's draw a complete circle with a radius of 50 to highlight the differences:

context.beginPath();
context.arc(100, 100, 50, 0, Math.PI * 2, false);

Note: The final parameter doesn't make any difference to the final circle here

Solid Circle

To turn this arc into a solid circle we need to call fill() which will fill in the circle and we should then have a black circle in the middle of the canvas:

<canvas width='200' height='200' id='canvas'></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.arc(100, 100, 50, 0, Math.PI * 2, false);
    context.fill();
</script>

If is possible to change the colour of the fill in a similar manner to how the stroke colour was changed, we simply change the variable fillStyle:

context.fillStyle = '#0000ff';

Remembering to make sure that it is changed before the call to the fill() method.

Stroked Circle

We simply use the aforementioned stroke() method again, and we should end up with a nice outline of the circle:

<canvas width='200' height='200' id='canvas'></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.arc(100, 100, 50, 0, Math.PI * 2, false);
    context.stroke();
</script>

Drawing Rectangles

This is super simple, especially following on from the circle section above. For rectangles we simply change the method arc() to rect() and change the parameters. The rect() method takes four very simple parameters:

So to draw a 50x50 square in the middle of the canvas we'd use:

context.rect(100, 100, 50, 50);

Simple as that.

Solid rectangle

For this example we'll also demonstrate changing the fill colour:

<canvas width='200' height='200' id='canvas'></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.rect(100, 100, 50, 50);
    context.fillStyle = '#0000ff';
    context.fill();
</script>

Stroked rectangle

Just taking the circle code and ammending as required:

<canvas width='200' height='200' id='canvas'></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    context.beginPath();
    context.rect(100, 100, 50, 50);
    context.stroke();
</script>

Adding Text

What if we want to write a message about how awesome canvas is? Well, that works with dedicated font methods, and yes - we can both stroke the text or fill it.

However, the methods are slightly differently named for text:

Both take 3 parameters:

Note: There is no need for any calls to beginPath() the one method does everything.

Solid text

There is no voodoo magic here or anything crazy. This will start the text at 10px from the left hand side, and 100px down with a message saying <3 Canvas

<canvas width='200' height='200' id='canvas'></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    context.fillText('<3 Canvas', 10, 100);
</script>

You might notice that the font size is a little small, and hard to read. Much like we could change the style of the fill and stroke, we can do the same with the font of the canvas, here we simply use a string assigned to the font variable - so for Helvetica in 40px we can use:

context.font = '40px Helvetica';

Stroked text

To truly highlight the stroked text, you'll want to make sure you use a larger font - so we'll be using the above font declaration to do this:

<canvas width='200' height='200' id='canvas'></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    context.font = '40px Helvetica';
    context.strokeText('<3 Canvas', 10, 100);
</script>

And that's text covered ... nothing complex or hard at all.

Combine Stroke and Fill

You are able to combine both stroking and filling in the examples so that you could have a shape or text that has a border but also a solid fill colour - for example green filled text with a black border:

<canvas width='200' height='200' id='canvas'></canvas>
<script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    context.font = '40px Helvetica';
    context.strokeText('<3 Canvas', 10, 100);
    context.fillStyle = '#00FF00';
    context.fillText('<3 Canvas', 10, 100);
</script> 

Stay Tuned

There are lots of settings that you can change associated with what we've used above - below are two examples:

In the next section on canvas, we'll cover adding in standard images, exporting what is in the canvas as an image and then after that we will move on to some basic animation and moving things on the canvas using the keyboard.

Tags: JavaScript, Canvas