HTML5: Drawing images and adding text to the canvas element

In the previous post, “HTML5: Working with the canvas element,” I reviewed several ways to manipulate this element, including creating rectangles, circles, triangles, and diamond shapes by drawing paths, and with various shades using rgba. In this segment we will review drawing images and playing around with adding text to the canvas.

The canvas drawImage function using JavaScript allows you to create an image object within the defined canvas area. The drawImage function includes three parameters and is expressed in the form drawImage(object image, float x, float y). The image file formats supported within the canvas element and drawImage function are .jpg, .gif, and .png. For the draw image function to work, we have to set the variable and define the image object. For this example, we set it to “img” as is expressed in var img = new Image(); and then the image source is provided, followed by the image onload, and the final drawImage function with the parameters defined as in the example below:

// Draw Image function
var img = new Image();
img.src = "images/Figure_A.png";
img.onload = function() {
context.drawImage(img, 145, 145);

The resulting canvas image is displayed below as shown in Firefox 3.6:

Figure A

(Read more…)