Getting started in HTML 5 Canvas

Canvas is a HTML tag for an interactive drawing surface. Its use is very simple.

To use it, three things are required:

  1. The HTML 5 doctype to the page.
  2. A <canvas> tag.
  3. A JavaScript script.

1) The HTML 5 doctype

It is especially necessary for Internet Explorer 9, it is absolutely required to specify the HTML 5 doctype on the first line of the page, as following:

<!DOCTYPE html>

For Internet Explorer you should add also:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

to avoid it changing the document mode when it can not validate it.

2) A canvas tag

An id est required to access the tag.

<canvas id="mycanvas" width="400" height="300"></canvas>  

This tag has no HTML content, but any message or content that appears only in older browsers that do not recognize HTML 5. Example:

<canvas id="mycanvas" width="400" height="300">
    Canvas is not implemented in this browser.
</canvas>   

3) A JavaScript script

The useful content is provided dynamically by JavaScript. For example, one can draw a blue rectangle.

canvas = document.getElementById("mycanvas"); 
if (canvas.getContext)
{    
    context = canvas.getContext('2d'); 
}
function rectangle()
{
   context.fillRect(100,0,80,80);     
}  

The script will be started by the onload event associated with <body> or window element.
In the example we create the function setCanvas () and assigns it to onload:

function initCanvas()
{
  canvas = document.getElementById("mycanvas"); 
  if (canvas.getContext)
  {    
    context = canvas.getContext('2d');
    return true; 
  }
 return false;
}

function setCanvas()
{
   if(! initCanvas()) return;
   context.fillStyle="blue"   
   context.fillRect(100,0,200,100);     
}  

window.onload=setCanvas;

The fillStyle attribute assigns a color to the current context, which will be used by all drawn objects thereafter. We can assign a color name, a rgb or rgba code.
The fillRect method shows a rectangle filled with the current color, and for parameters: x, y, width, height.

Demonstration (Firefox, Chrome, Internet Explorer 9):

Nothing is displayed in Internet Explorer 8 and older versions which do not recognize the canvas tag.

List of graphics functions of the Canvas API

Look at this demo

See also