Getting started in HTML 5 Canvas
Canvas is a HTML tag for an interactive drawing surface. Its use is very simple.
Actually, only three things are required to use it:
- An HTML page with the HTML 5 doctype.
- A <canvas> tag.
- Some JavaScript code.
1) The HTML 5 doctype
It is essential to specify a DOCTYPE on the first line of the page, which for HTML 5 has the following form:
<!DOCTYPE html>
2) A canvas tag
The tag must have an "id" attribute so that it can be referenced in JavaScript code:
<canvas id="mycanvas" width="400" height="300"></canvas>
This tag has no HTML content, but possibly some message that will appear only in older browsers that do not support HTML 5. Example:
<canvas id="mycanvas" width="400" height="300">
Canvas is not implemented in this browser.
</canvas>
3) A JavaScript script
The content of <canvas> 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 this 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, Edge, Safari, Opera):
List of graphics functions of the Canvas API
- Canvas Element. W3C spec.
Look at this demo
- Zoomquilt. In the same spirit than infinite Oz, that is made in Flash, but this time in JavaScript on Canvas, endless picture that besides entertainment it provides, allows to compare the speed of the browsers.
See also