html5-canvas Loading and displaying an Image


To load an image and place it on the canvas

var image = new Image();  // see note on creating an image
image.src = "imageURL";
image.onload = function(){

Creating an image

There are several ways to create an image

  • new Image()
  • document.createElement("img")
  • <img src = 'imageUrl' id='myImage'> As part of the HTML body and retrieved with document.getElementById('myImage')

The image is a HTMLImageElement

Image.src property

The image srccan be any valid image URL or encoded dataURL. See this topic's Remarks for more information on image formats and support.

  • image.src = ""
  • image.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=" *

*The dataURL is a 1 by 1 pixel gif image containing black

Remarks on loading and errors

The image will begin loading when its src property is set. The loading is syncriouse but the onload event will not be called until the function or code has exited/returned.

If you get an image from the page (for example document.getElementById("myImage")) and its src is set it may or may not have loaded. You can check on the status of the image with HTMLImageElement.complete which will be true if complete. This does not mean the image has loaded, it means that it has either

  • loaded
  • there was an error
  • src property has not been set and is equal to the empty String ""

If the image is from an unreliable source and may not be accessible for a variety of reasons it will generate an error event. When this happens the image will be in a broken state. If you then attempt to draw it onto the canvas it will throw the following error

Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.

By supplying the image.onerror = myImgErrorHandler event you can take appropriate action to prevent errors.