An example of using images with canvas

Posted on 24th April 2013

A guide explaining how to draw images on your canvas tag using the drawImage function. The function is quite versatile and comes in three main flavours.


To add an image to your canvas you can use the context.drawImage() function. This function comes in three variants and can be used to add images to your canvas at the coordinates that you specify. For example:

* The three argument version of the function allows you to specify the x/y coordinates of where
* the image will be placed
context.drawImage(img, x, y);

* The five argument version of the funcrtion allows you to shrink or enlarge the image to fit
* your chosen dimensions.
context.drawImage(img, x, y, w, h);

* The nine argument version of the function allows you to specify the portion of the image
* that should be displayed - ie the colored section of the image below.
context.drawImage(img, sx, sy, sw, sh, x, y, w, h); // Note the order of the arguments
An illustration of the 9 argument variant of the drawImage function [No canvas support]

This canvas shows an example of all three of the drawImage variants.

The first is a stright-forward call that draws the image at the coordinates that you give. The top left corner of the image is placed at the coordinates - so if you want to align it differently you'll need to do a little bit of arithmetic.

The second allows you to set the width and height for the image. The dimensions of the image will be scaled to fit in the image - so it will either be stretched or shrunk to fit the dimensions that you specify.

The third is similar to the second - but additionally it allows you to secify which part of the image that you want to display. So you can think of it as a "crop" that you can use to specify the coordinates of a rectangular portion of the image that you want to display. The image on the right shows you how this variant works.

The image must be loaded before you call drawImage()!

It's important to remember that any image that you want to be drawn on the canvas must be loaded before-hand. This means that you must either load the image before you start drawing on the canvas or that you use the images onload event to call the context.drawImage() - like this:

var img = new Image();
img.src = '/images/logo.png';
img.onload = function (e)
    context.drawImage(img, 5, 5);

This may mean that you either have to reorganise your code in order to account for the potential delay in loading the image (so that you can draw on top of it for example). Or that you ensure all your images are loaded first before you start drawing on the canvas.

Examples of the drawImage function


Add a new comment...