<canvas> tag can be considered the most important addition to HTML family.
It allows you to draw anything you want in your browser.

What is actually <canvas> tag?

<canvas> tag was added in HTML5 as an element that allows the browser / client to draw shapes and images without any plugin.

Using only JavaScript you can create pieces of code that will do the painting in the canvas.

How to unlock <canvas>'s potential?

Declare a <canvas> tag

To declare a canvas tag you simply add it as a normal HTML tag
<canvas id="mycanvas" width="400" height="300">Your browser does not support HTML5</canvas>						
As you can see <canvas> has normal properties :
  • id – the id identifier in DOM structure. Later you will see that it is used to access canvas element
  • width – the width of the canvas
  • height – the height of the canvas

Fall back option

Your browser might no support <canvas> so at least you can provide your users a clue about that.
To do that you can add text or images inside the <canvas> tag.

In our example we have a message “Your browser does not support HTML5” that will warn user about this issue.

Another option would be to display a static image (JPG or GIF) with a mockup of how the canvas will look if it will work.

Obtain context

To be able to actually use the <canvas> engine you have to access it. In order to do that you have to use JavaScript to get access the <canvas> element and once you grab it you can access its “2d” context.

To access the <canvas> element is a standard document.getElementById call:

var eMyCanvas = document.getElementById('mycanvas');
						
Once you have it you need access to its context. As canvas will, in near future, have also a 3D engine you have to pick what engine to use. We need “2D” engine (for now :) )

var ctx = eMyCanvas.getContext('2d');
						

Basic example

Now you can draw, for example, a rectangle

ctx.fillRect(0, 0, 100, 100);
					

Bellow is the LIVE example

Bellow is code

var eMyCanvas = document.getElementById('mycanvas');
var ctx = eMyCanvas.getContext('2d');
ctx.fillRect(0, 0, 100, 100);
ctx.stroke();