Having fun with HTML5 – Canvas, part 1

One of the cool new features introduced by HTML5 is the new <canvas> tag, which defines an area for you to draw graphics on using javascript.


To create a canvas element is as easy as inserting a <canvas> tag like this:

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

Typically you will give it an ID as you will need to look it up with javascript later in order to do anything with it, and as for the javascript, pretty much all javascript that interacts with the canvas need to start with something 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 plumbing code to check whether the browser supports the <canvas> tag and if element is not null and that the getContext method exists, etc. The easiest way to check for browser support for the <canvas> tag would be to use a simple library like Modernizr, and all you need is to check the .canvas 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 context (specification for a 3D context is in the pipeline and some vendors have released their own 3D context API) you can use it to draw paths, shapes, text, etc. etc.


Seeing as all the action around a canvas element is centred around the 2D context, it’s only fitting that it gets its own specification. The full specification (work in progress of course) of the 2D context object can be found here.

Have a look at the links in the References section for some useful articles which go through the various API calls you’ll likely need to use in detail.

Resetting a canvas

Setting the width or height of the canvas element will erase its contents and reset all the properties of its drawing context to their default, so something like this will suffice:

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


Once you’ve had a chance to look at the basic API methods, I’ve put together a quick example here to demonstrate how to draw some basic gradients using two stop and how to draw a chessboard using the fillRec and strokeRect 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); } } } } [/code] The baseX and baseY are set to 0.5 for the reason explained in the Dive into HTML5 article (see reference), that if you draw a one pixel wide line between whole number coordinates you will end up with a two pixels wide line instead.

The rest is fairly straight forward and draws a 8×8 chessboard of alternating empty and filled squares, left to right, top to bottom, with the first square being unfilled.


Dive into HTML5 – Canvas

Mozilla Developer Center’s canvas tutorial

Related posts:

Having fun with HTML5 – Canvas, part 2

Having fun with HTML5 – Canvas, part 3

Having fun with HTML5 – Canvas, part 4

Having fun with HTML5 – Canvas, part 5

Enjoy what you’re reading? Subscribe to my newsletter and get more content on AWS and serverless technologies delivered straight to your inbox.

Yan Cui

I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.

You can contact me via Email, Twitter and LinkedIn.

Hire me.

Check out my new course, Complete Guide to AWS Step Functions.

In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, design patterns and best practices.

Get Your Copy