Getting started in HTML 5 Canvas
Canvas is an interactive drawing surface implemented in HTML with a tag.
To use it, three things are required:
- The HTML 5 doctype to the page.
- A <canvas> tag.
- A JavaScript script.
The HTML 5 doctype
Under Internet Explorer 9, it is absolutely required to specify the HTML 5 doctype on the first line of the page, and it is as following:
<!DOCTYPE html>
For Internet Explorer you should add:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
to avoid it changing the document mode when it can not validate it.
The canvas tag may hold a text
<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>
A simple script: Displaying a blue rectangle
The useful content is provided dynamically by JavaScript. For example, one can draw a 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):
List of graphics functions
- The Canvas Element. WHATWG.
- Canvas 2D Context. W3C spec.
