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 = 'http://img.authorcode.com/ac/2013/04/html5.jpg'

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:

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

Author: Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.