Loading and displaying an Image

suggest change

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(){
    ctx.drawImage(this,0,0);
}

Creating an image

There are several ways to create an image

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.

*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

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.

<!– Hidden example notes.

The intent of this example is show the most basic way off loading and displaying an image and some info on variations and alternatives approaches.

–!>

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents