Wednesday, 18 May 2011

Display Image on Canvas (Introduction to HTML5 Canvas)

This is about the simplest example of the use of HTML5 canvas you can get. This is to introduce you to the HTML5 canvas, to show how the canvas can be set up and drawn in. Once you've got this down, you can move onto using the canvas in more interesting ways.

Firstly, you would have this in the html of the page:
<canvas id="canvas" width="400" height="400">
Browser not compatible with HTML5 canvas
</canvas>
The id of the canvas element has been set to "canvas", which is how the javascript can identify the right canvas element to manipulate.
The width and height of the canvas will be 400px.
And if an incompatible browser is used, it will display the text "Browser not compatible with HTML5 canvas".


And here is an example of the kind of javascript you could use to draw an image (you could have this in script tags or have it in a .js file and call it from src attribute of script tags):
var canvas = document.getElementById('canvas');
var context2D = canvas.getContext('2d');

var img = new Image();
img.src = "http://www.blogger.com/img/logo40.png";
context2D.drawImage(img, 100, 50);
So first it gets the canvas element by using the id we gave it. It then creates the 2D context with that canvas element.
It then loads a new image object and then tells it to use the image from http://www.blogger.com/img/logo40.png by assigning it to the src variable of the Image object.

Then it uses the 2D graphics API by calling the drawImg() function.
The first parameter of the function is looking for an image object, the second is the x-position and the third is the y-position.


So here it is (I added style="background-color: #A9A9A9;" to the canvas so you can see it fully):
Browser not compatible with HTML5 canvas
So there we go, that is an extremely simple use of the canvas. This is just to get you kick-started.
Here's a pastebin of an example full HTML file for this: http://pastebin.com/zrsrdAGP