Having fun with HTML5 – Canvas, part 1

You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!

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.

Basics

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.

API

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;

Demo

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.

References:

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 I help companies go faster for less by adopting serverless technologies successfully.

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.


Skill up your serverless game with this hands-on workshop.

My 4-week Production-Ready Serverless online workshop is back!

This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.

We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.

If you enrol now you can also get 15% OFF with the promo code “yanprs15”.

Enrol now and SAVE 15%.


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!