Canvas Tutorial - Graphics in a browser

The Canvas tag is defined in the new HTML 5 format for web pages, and already implemented on most browsers.
It allows you to display 2D graphics in the browser and thus make it a platform for rich web applications.

How use Canvas

It has only two attributes: width and height, in addition to generic attributes like id, name, class ... Its purpose is to mark the location where you want to insert a drawing surface (technically called "rendering context").

The body of the tag is not displayed by browsers that implement Canvas but only by others, and is therefore a means of providing alternative content.

Using Canvas is very simple, the code below shows a minimal application:

<canvas id="c1" width="400" height="100"> 
    Not implemented. 
 </ canvas> 

This has defined a location and its ID, it remains to add a graphic content:

var canvas = document.getElementById (c1);  
if (canvas.getContext) 
{ 
   var ctx = canvas.getContext ('2d');  
   ctx.fillRect (100,0,80,80);       // displays a full rectangle 
}  

To start the script you can use the onload event associated with the <body> tag or the window element. In the demo we create the function canvasFun() and it is assigned to onload:

window.onload=canvasFun; 

We'll see in future articles the graphical methods and their use.

Canvas test and demo

This script allows to check if Canvas is implemented on you browser and shows some very simple applications of this HTML 5 tag.

The images will be displayed on all recent browsers.

Displaying a blue rectangle

Not supported!

HTML code

<canvas id="c1" width="400" height="100">
Not supported!
</canvas>

Displaying a green circle

Not supported!

HTML code

<canvas id="c2" width="400" height="100">
Not supported!
</canvas>

JavaScript code

function canvasFun()
{
  var canvas = document.getElementById('c1');
  if (canvas.getContext)
  {
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = "rgb(0,20,180)";
    ctx.fillRect(100,0,80,80);
  }
  var canvas = document.getElementById('c2');
  if (canvas.getContext)
  {
    var ctx = canvas.getContext('2d');
    ctx.strokeStyle = "rgb(0,128,0)";
    ctx.arc(140, 45, 40,0, Math.PI+(Math.PI*2)/2,true);
    ctx.stroke();
  }
}
window.onload=canvasFun;

The CanvasFun function draws a filled rectangle in the first canvas tag and a circle in the second.
But if the tag is not recognized by the browser, this is the text inside that is displayed.

Resources

© 2008-2022 Xul.fr