Introduction to HTML5 canvas element

07 August 2012Zofia Korcz

Deliver high interactivity levels and multimedia to the end user - it's no longer a nice to have but a norm now. For quite a while now, we've had plugins like Flash, Silverlight or Java responsible for media integration jobs. They were good some time ago, when desktop computers dominated whole digital market. Nowadays, with the more than rapid proliferation of mobile devices, delivering fast and robust websites with supporting multimedia is more important than ever.

HTML5 adds new features to help you provide the rich interactivity without installing any additional plugins. One of these new features is the canvas element.

Canvas element

What is canvas in html5? Simply put, it is an element defined in the HTML5 code which allows us to draw various raster-based images. Using JavaScript, we can draw single geometric 2D figures, load images and other media or even animate movement for those elements.  

You are probably wondering as to what is so special about canvas and why you should really care about it in the age of flash technology and ActionScript?  

Here are good reasons  

1 - Canvas as part of HTML5 is totally free and open! It means, that the developers don't need expensive software like 'Adobe Flash' to actually code. Open code also means, that learning new things is much easier, because everything a developer wants to know is visible in the source of an HTML5 site (like any JavaScript code).  

2 -  No more plug-ins! You don't need to compile anything, just write code and watch results in a browser. That leads us to another big advantage of the canvas element. It simply doesn't need any browser plug-ins either like Adobe Flash Player.  

3 - Accelerated performance

Modern browsers shift graphic tasks to a GPU for faster processing instead of a CPU. In such a situation, it is a CPU that takes over other tasks more efficiently, so overall performance is accelerated.

With this post, I would like to show you how to define a simple canvas element and how to perform some primary operations in JavaScript which helps us modify that element. I have included some examples that include rectangles, arcs, custom shapes, images and more sophisticated curves.

First glimpse at canvas element

Let’s begin with a simple canvas definition! How to write a basic canvas element in html5? It's as simple as :

<canvas id="myCanvas" width="100" height="100">
Your browser does not support the canvas element.

It's just like any other block element. We can define its dimensions (in this example its width="100" height="100") but in case you don't specify that, canvas will take on default values (which are 300 for its width and 150 for its height). If a browser doesn't support the canvas element, it will just show that element callback. That callback message is defined between <canvas> and </canvas> markups.  

OK, now let's do some 'magic' in JavaScript!

First of all, we need to create a context of canvas. That context returns an object that exposes an API for drawing on the canvas. This is how you can do it in JavaScript:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

We have the context, so now we can make some drawings.

Basic shapes

Here is a simple example of basic shapes in canvas:

context.fillStyle   = '#D3E9ED'; // blue
context.strokeStyle = '#ED2024'; // red

// Draw some rectangles.
context.fillRect  (10, 10, 50, 50);
context.strokeRect(10, 70, 50, 50);

The context.fillStyle attribute is used to define the color of fulfillment. Note that here, we are referring to the context defined previously. The context.strokeStyle attribute is similar to context.fillStyle but this time only a stroke is defined.

The two methods used for drawing rectangles are context.fillRect and context.strokeRect. They are both very similar, the only difference is that context.fillRect fulfills the defined shape and context.strokeRect draws only borders of the defined shape. Each of these functions takes the same parameters which are x and y which specify the position on the canvas of the top left corner of the rectangle and the width and height of the rectangle. Note that the origin of the grid is positioned in the top left corner and all elements are placed relative to this origin.



The above examples shows how to draw arcs (and circles) on the canvas. context.beginPath() resets list of sub-paths, which allows us to draw new shapes. Method arc() has five parameters. The first two are coordinates of the circle's center, third is the radius of the circle (in radians), next two are the start and end angles. The last one is a Boolean value which specifies whatever the circle is drawn counterclockwise or clockwise.

context.moveTo(140, 10);
context.lineTo(180, 10);
context.lineTo(140, 50);
context.lineTo(140, 10);

This code exemplifies how to draw more sophisticated shapes. We can use lines and paths to do that. The above code shows the method how to draw a line (and fulfill it with color defined a few lines before) and connect them between given coordinates. context.moveTo() determines the beginning of the new shape coordinates.

context.moveTo(180, 80);
context.lineTo(180, 120);
context.lineTo(140, 120);
context.lineTo(180, 80);

This example is very similar to the previous one. The main difference is that in here we have only a stroke of the shape without any fulfillment.

Loading images

We already know how to draw various shapes in canvas. Now, lets see how you can load images and show them in the canvas element.

var myImage = new Image();
myImage.src = "logo.jpg";
myImage.onload = function() {
context.drawImage(myImage, 30, 15, 130, 110);


 As you can see, it's quite easy and similar to drawing rectangles. We just need to specify the image object and after loading it, deliver its coordinates and dimensions to the canvas context.

Drawing curves

The canvas API offers also methods for drawing Bézier curves. Bézier curves are used to model smooth curves. There are two main types of those curves: cubic and quadratic. We have methods for both of them in canvas: quadraticCurveTo(cp1x, cp1y, x, y) and bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y). X and Y in both methods are the coordinates of destination point. cp1x, cp1y and cp2x, cp2y are coordinates of control points.  

More information about quadratic, Bézier curves and their control points can be found here or even here.

Here is a simple (but little time-consuming) demo of Bézier curves in action:

context.strokeStyle = '#BDD74A'; // green
context.lineWidth   = 3;


context.strokeStyle = '#007BC2'; // blue

 All the demos, I've referenced are available on


As you can see, the canvas element offers a big variety of shapes and functions. In conjunction with the JavaScript language it can be a very powerful and useful tool. We already know how to draw basic shapes, load images and create complex curves. There are lots of other cool stuff we can do! For example, use event handlers to detect mouse movements and draw custom figures depending on the mouse position. Here is an example of a little bit more sophisticated operations in JavaScript and canvas

The canvas element can also be used to render text, draw gradients and shadows and to scale, rotate and transform drawn shapes. But maybe let's save it for another post ;).

If you are interested in diving more into the canvas API, here are some more links worth reading: 

- Dive into HTML5

- Mozilla Canvas Tutorial

- Microsoft HTML5 Canvas Tutorial

- w3 2dcontext

I'd obviously love to know what you get to with the canvas so please do provide your feedback!

Author: Zofia Korcz
Published: 07 August 2012
front-enddevelopmenttechnologyopen sourcetool

People in or team love to share their experience. Explore our blog

Job Opportunities

We're always looking for new faces to join the Cognifide family. Take a look at our available jobs.