Having fun with HTML5 – Canvas, part 1

Check out my new course Learn you some Lambda best practice for great good! and learn the best practices for performance, cost, security, resilience, observability and scalability.

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

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter

Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.

Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.

Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!

Check out my video 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. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!

Are you working with Serverless and looking for expert training to level-up your skills? Or are you looking for a solid foundation to start from? Look no further, register for my Production-Ready Serverless workshop to learn how to build production-grade Serverless applications!

Find a workshop near you