Bitmap Graphics with HTML5 Canvas
2012-05-27
Introduction
The <canvas> element supported by HTML5 allows for 
creation of both vector graphics and bitmap graphics. Bitmap graphics have been 
available for use in a browser for decades using the <img> tag, but 
integrating bitmap graphics into <canvas> elements enables us to do more 
dynamic things with our graphics.
This article will show how to load a bitmap image, specifically a PNG file, into a <canvas> element using JavaScript.
Creating the Canvas Element
The HTML tag used to create a canvas element is 
<canvas>.
<canvas id="canvas1" width="300" height="200" ></canvas>
We have given the element an ID of "canvas1" so that it can be easily referenced using JavaScript.
Loading an Image
In Javascript we need to create a new Image() object, which we will use to load our bitmap image:
var turtleImage = new Image();
An image can be loaded into this object by setting the "src" attribute of the object. The src attribute needs to be set to a valid URL.
turtleImage.src = "turtle.png";
Displaying the Image
Now that we have loaded a bitmap image, we need to display it within the canvas. First, we will locate the canvas:
var canvas = document.getElementById('canvas1');
Then we need to get the 2D drawing context layer of the canvas object:
var ctx = canvas.getContext('2d');
Lastly, we use the drawImage() method to display the bitmap 
image. We must provide drawImage() with the Image() 
object that we wish to display, along with the coordinates on the canvas where 
we want to locate the image:
ctx.drawImage(turtleImage, 50, 50);
Making Sure the Image Has Loaded
Unfortunately, if you try call the drawImage() function before 
the browser has finished loading the image, the image will not be displayed.
Because of this, we need to make sure that loading is complete first:
turtleImage.onload = function () {
	ctx.drawImage(this, 50, 50);
}
Putting It Together
Combined together, the JavaScript code needed to display a bitmap image within the canvas is:
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
var turtleImage = new Image();
turtleImage.onload = function () {
	ctx.drawImage(this, 50, 50);
}
turtleImage.src = "turtle.png";
Demo
If you are using a modern browser, you should be able to use the demo below to display the 'turtle.png' image in random locations on the canvas: