I consider HTML5 canvas the backbone of all the features available in HTML5, i recently got chance to work on a HTML5 application and really enjoyed learning new things and was really impressed with myself. Actually anyone who already knows some JavaScript and traditional HTML can kick start working on it.
For those who have just started working on it, i have created a Hello world application, this is a simple application, but will give overall view of how it works. Like in our graduation we always create a Hello world application to get start learning things, so here how it works:
First of all we should know whether the browser supports HTML5 canvas, for this you can view my post at
Check if browser supports HTML.
I will use following method:
function supports_canvas() {
//Check if browser supports canvas
return !!document.createElement('canvas').getContext;
}
Next we need a Canvas element which supports 2D graphic drawings, it is the canvas on which we can draw different shapes like circle, rectangle, arcs, circle, etc also we can write text, and draw images from some source files.
This sample focuses on creating a canvas and writing hello world on it. For this i will create a DIV element in my document, than add a Canvas element in the DIV using JavaScript:
function initializeCanvas(containerid, canvasWidth, canvasHeight) {
var container = document.getElementById(containerid);
if ( supports_canvas() ) {
//Create canvas element
var canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
container.appendChild(canvas);
//Context of canvas for performing 2d graphics operations
context = canvas.getContext('2d');
return context;
} else {
container.innerHTML = 'This is a HTML5 app,
you need a HTML5 capable browser like Firefox,
Chrome, Safari or Internet Explorer 9.'
return null;
}
}
Here is the working sample:
Sample Hello World