Get started with HTML5 – Canvas

Playing games on the internet using Silverlight or Flash is getting really popular, which you can see if you are using Facebook (Farmville, anyone?). To play these games you need to install a plugin to your browser, or you won’t be able to play them. On some devices you can´t install plugins like these, which make it impossible to play them. Instead you will have to create separate applications for each device, but then you will have to maintain several versions of your application.

To get it to work in a smooth way on computers, phones and other devices you can use Canvas. Canvas is part of the HTML5 specification, and makes it possible to draw objects on the screen using JavaScript APIs.

In my examples I use Internet Explorer 9 which supports hardware acceleration for Canvas, but you should be able to use the same code on all modern browsers.

Create a canvas object

To be able to use Canvas on the page, we will need to use the new Canvas element in HTML5.

I have created a template which I will use:

<!DOCTYPE HTML>
<html>
<head>
    <title>Canvas</title>
    <script>
 
    </script>
    <style>
        body
        {
            background-color: #000;
            text-align: center;
        }
        
        div
        {
            margin: 0px auto;
            width: 400px;
        }
        
        canvas
        {
            background-color: #fff;
        }
    </style>
</head>
<body>
    <div>
        <canvas id="canvas" width="300" height="300">
            Your browser does not support Canvas.
        </canvas>
    </div>
</body>
</html>

I use the new HTML5 doctype to tell the browser that I´m using HTML5 here. I also add a Canvas element which is 300x300 pixels. If we open the site in a browser without Canvas support, the text will be displayed, and if we open it in Internet Explorer 9, we will get this:

canvas0

The white area is our canvas where we will start drawing objects. First of all, I would like to set the background to a linear gradient which shows red and white.

To do this, I add the following code between the script elements:

function init() {
    var c = document.getElementById('canvas');
    var ctx = c.getContext('2d');
 
    var grad = ctx.createLinearGradient(0, 0, 300, 300);
    grad.addColorStop(0, '#FFFFFF');
    grad.addColorStop(0.5, '#FF0000');
    grad.addColorStop(1, '#FFFFFF');
    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, 300, 300);
}

If we take a look at the page again, we will see this:

canvas1

When you want to draw on a canvas you will first have to get the canvas object. I use document.getElementById here, but you could use jQuery selectors as well to get the element. The next step is to create a 2d context, which is the only available context in HTML5. The object we get here is what we will use to draw on the canvas.

Now when we have the canvas element and have got the 2d context, we can start drawing on it. What we want is a gradient that starts on the upper left (0,0) and stops at the lower right (300,300) in the current LinearGradient object.

Then we set the colors we want. It should start with white, be red in the middle, and then stop as white again. Notice that 0 is the start and 1 is the end, which makes 0.5 the middle.

At last we will fill the canvas element with the gradient we just created. To do this, we sett fillStyle to “grad” which is our object, and then call fillRect() where we set the start and stop for the drawing.

Now we will get a gradient background!

Draw patterns

With only a background we will probably don´t get far, what we need to do is to add other objects on the canvas.

The next step here is to draw a transparent square with shadows on top of the background.

What we will add after the previous code is:

ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
ctx.shadowBlur = 5;
ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
ctx.fillStyle = 'rgba(0, 0, 255, 0.3)';
ctx.fillRect(50, 50, 200, 200);

We are still using the same object as before, but continue to draw on the canvas after we have set the background.

First we will have to set the shadow on the object we want to draw. I have set offset to 3 for both X and Y, which gives us a 3px shadow. I have also set shadowBlur to 5, which settles how blurred the shadow should be (a higher number makes it blurrier). I also set the color on the shadow to black, but the opacity to 0.7 to make it more transparent.

When we have set the properties for the shadow we will set the color for the object to draw. We will use RGBA here too since we wants the square to be transparent. I set the color to blue and opacity to 0.3.

The last thing to do is to draw the object on the canvas. It should be positioned 50px from the top and the left, and should be 200x200px.

If we look at the site again we will see this:

canvas2

With a little help from our beloved friend JavaScript, we have done what we earlier should have had to use a real image for. Since it´s JavaScript we can make this process much more dynamic.

Animate the square

To make it do something, we can animate the canvas. Since there is not state for the objects in the canvas, we will have to keep track of that ourselves. What we will do here is a very simple animation where the square will move between two different positions every 500 millisecond.

To make it easier to animate the canvas, I will move the code for drawing the object to a separate function. I will call this function when the page is first loaded, and then every 500 millisecond. The code needed to do this is:

var position = 75;
 
function init3() {
    drawImage();
    setInterval(function () { drawImage(); }, 500);
}
 
function drawImage() {
    var c = document.getElementById('canvas');
    var ctx = c.getContext('2d');
 
    var grad = ctx.createLinearGradient(0, 0, 300, 300);
    grad.addColorStop(0, '#FFFFFF');
    grad.addColorStop(0.5, '#FF0000');
    grad.addColorStop(1, '#FFFFFF');
    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, 300, 300);
 
    ctx.shadowOffsetX = 3;
    ctx.shadowOffsetY = 3;
    ctx.shadowBlur = 5;
    ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
    ctx.fillStyle = 'rgba(0, 0, 255, 0.3)';
    ctx.fillRect(position, position, 200, 200);
 
    position = (position == 25) ? 75 : 25;
}

We are using pure JavaScript to draw an animated object on the screen using only web standards. This is probably not the most advanced example you will ever see, but there are far more advanced games out there. A good source for Canvas based games is http://www.canvasdemos.com where you can find a lot of games and programs that won´t need a third party plugin.

Since Internet Explorer 9 have hardware acceleration for Canvas, it is going to be possible to write really advanced games and applications which will use the graphic card to render your canvas, and all this is possible using only HTML5 and JavaScript!

No Comments