HTML5 canvas – Loading An Image

HTML5 canvas element has the ability to use the images. Firstly to load or draw the image on the canvas element we need to create the HTMLImageElement object and then use the drawImage() function. drawImage() function can accept several parameters.

Draw Image from the src attribute

So let’s start with object of Image element as:

var img = var img = new Image();

Set the src attribute to the object of image:

img.src = ''

After loading the image:

The next step to set the this image on to the canvas with the help of drawImage function. Here it need to notice that if you call drawImage() function before loading image then it won’t do anything. So we write the drawImage on the load event of the image object. This event will be fire after loading the image.

img.onload = function() {
// call the function drawImage

Full Code:

    <title>Load image in HTML5 Canvas</title>
#maindiv canvas{border:1px solid #bbb;}
    <script type="text/javascript">
        var  ctx1;
 function init() {
     can1 = document.getElementById("MyCanvas1");
     ctx1 = can1.getContext("2d");
	 var img = new Image(); 
	 img.src = '';
     img.onload = function() {
        can1.width = img.width +20;
        can1.height = img.height +20;
<body onload="init();">
<div id="maindiv">
    <canvas id="MyCanvas1" width="300" height="200">
  This browser or document mode doesn't support canvas object</canvas>