One of the cool new fea­tures intro­duced by HTML5 is the new <can­vas> tag, which defines an area for you to draw graph­ics on using javascript.

Basics

To cre­ate a can­vas ele­ment is as easy as insert­ing a <can­vas> tag like this:

<canvas id="myCanvas" width="400" height="400"></canvas>

Typ­i­cally you will give it an ID as you will need to look it up with javascript later in order to do any­thing with it, and as for the javascript, pretty much all javascript that inter­acts with the can­vas need to start with some­thing along the line of:

// get the element by ID
var element = document.getElementById("myCanvas");

// get the 2D context which is what you use to draw
var context = element.getContext("2d");

To make this more robust you’re likely to need more plumb­ing code to check whether the browser sup­ports the <can­vas> tag and if ele­ment is not null and that the get­Con­text method exists, etc. The eas­i­est way to check for browser sup­port for the <can­vas> tag would be to use a sim­ple library like Mod­ern­izr, and all you need is to check the .can­vas property:

<script type="text/javascript" src="modernizr/modernizr-1.6.min.js"></script>
…
$(document).ready(function () {
    // check if canvas is not supported
    if (!Modernizr.canvas) {
        // fall back logic here
    } else {
        // normal steps here
    }
});

Once you’ve got the 2D con­text (spec­i­fi­ca­tion for a 3D con­text is in the pipeline and some ven­dors have released their own 3D con­text API) you can use it to draw paths, shapes, text, etc. etc.

API

See­ing as all the action around a can­vas ele­ment is cen­tred around the 2D con­text, it’s only fit­ting that it gets its own spec­i­fi­ca­tion. The full spec­i­fi­ca­tion (work in progress of course) of the 2D con­text object can be found here.

Have a look at the links in the Ref­er­ences sec­tion for some use­ful arti­cles which go through the var­i­ous API calls you’ll likely need to use in detail.

Reset­ting a canvas

Set­ting the width or height of the can­vas ele­ment will erase its con­tents and reset all the prop­er­ties of its draw­ing con­text to their default, so some­thing like this will suffice:

var canvas = $("#myCanvas");
canvas.width = canvas.width;

Demo

Once you’ve had a chance to look at the basic API meth­ods, I’ve put together a quick exam­ple here to demon­strate how to draw some basic gra­di­ents using two stop and how to draw a chess­board using the fill­Rec and stro­keRect methods:

// draws a chessboard
function drawChessboard() {
    // define the constants
    var baseX = 0.5, baseY = 0.5, width = 50;
    // get the 2D context from the "chessboard" canvas
    var context = document.getElementById("chessboardCanvas").getContext("2d");

    // draws the 8 by 8 chessboard
    for (var i = 0; i < 8; i++) {
        for (var j = 0; j < 8; j++) {
            var x = baseX + width * i, y = baseY + width * j;

            // draw the rectangle
            context.strokeRect(x, y, width, width);

            // fill the odd number rectangles
            if ((i + j) % 2 != 0) {
                context.fillRect(x, y, width, width);
            }
        }
    }
}

The baseX and baseY are set to 0.5 for the rea­son explained in the Dive into HTML5 arti­cle (see ref­er­ence), that if you draw a one pixel wide line between whole num­ber coor­di­nates you will end up with a two pix­els wide line instead.

The rest is fairly straight for­ward and draws a 8x8 chess­board of alter­nat­ing empty and filled squares, left to right, top to bot­tom, with the first square being unfilled.

Ref­er­ences:

Dive into HTML5 – Canvas

Mozilla Devel­oper Center’s can­vas tutorial

Related posts:

Hav­ing fun with HTML5 — Can­vas, part 2

Hav­ing fun with HTML5 — Can­vas, part 3

Hav­ing fun with HTML5 — Can­vas, part 4

Hav­ing fun with HTML5 — Can­vas, part 5

Share

7 Responses to “Having fun with HTML5 — Canvas, part 1”

  1. […] Ear­lier I explored some of the basic draw­ing meth­ods avail­able on the 2D con­text of the new can­vas ele­ment in HTML5, mov­ing on from there, I’ve put together another quick demo here (see image below) which lets the user scrib­ble inside the can­vas element. […]

  2. […] Hav­ing fun with HTML5 — Can­vas, part 1 […]

  3. […] it does mean that I need to change the way I’m clear­ing the can­vas for each frame though. In part 1 of this series I men­tioned that by set­ting the width or height of the can­vas ele­ment you […]

  4. Richard says:

    Hi
    Thanks for this can­vas arti­cle.
    I have played around with the chess­board exam­ple but have a prob­lem with it.
    I made the can­vas area larger & want to posi­tion the chess­board in the can­vas div but it ‘sticks’ to the top left cor­ner of the can­vas div area no mat­ter what I do!
    How can I repo­si­tion this board? Most grate­ful for advice –many thanks

  5. theburningmonk says:

    Hi Richard,

    Do you have your code some­where so I can take a look and see what’s wrong with it? If you don’t want to make it pub­licly avail­able, feel free to email it to me instead at theburningmonk@gmail.com.

    So chang­ing the ‘baseX’ and ‘baseY’ val­ues have no effect on the posi­tion of the chess­board inside the can­vas div?

  6. Richard says:

    Hi tbm
    Thanks for your prompt & help­ful reply which has fixed the prob­lem for me.
    I obvi­ously did not under­stand var BaseX 0.5 & BaseY 0.5.
    Sim­ply chang­ing baseX & baseY val­ues to the coor­di­nates I want then posi­tions the chess­board appro­pri­ately as you advised. A 2 pixel bor­der width is not a prob­lem for me here.
    Many thanks.

    As an aside I now want to add board coor­di­nates around the edge of the board & can­not yet find a method to do this! I would be very grate­ful for your sug­ges­tion (ie 1–8 along side y axis/a-h below x axis). I tried adding divs to can­vas ele­ment with no success..

  7. theburningmonk says:

    Hi Richard,

    Try increas­ing the baseX and baseY val­ues to allow suf­fi­cient space on the top and left of your chess­board and then work out where the coor­di­nates should be shown and then use context.fillText to draw the coor­di­nates.
    Have a look at some exam­ples here: http://diveintohtml5.info/canvas.html

Leave a Reply