Summary -

In this topic, we described about the Draw Image with detailed example.

In the html5, we use drawImage() method for drawing an image on the canvas. This method also draws parts of an image and increase or decrease the image size.

drawImage( ) method involves with an image object and a destination point. The destination point describes the top left corner of the image comparative to the top left corner of the canvas. In the image object, we should initially establish an image and wait for it to load before initiating drawImage( ) method. We can achieve this by utilizing the onLoad property of the image object.

Syntax -

Position the image on the canvas -

context.drawImage(img,x,y);

Position the image on the canvas, and stipulate height and width of the image -

context.drawImage(img,x,y,width,height);

Clip the image and position the clipped part on the canvas -

context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);

The below table describes the parameter values of the draw image method -

Parameter Description
img Stipulates the image, video element to utilize.
img Stipulates the image, video element to utilize.
sx The x coordinates where to begin clipping.
sy The y coordinate where to begin clipping.
swidth The width of the clipped image.
sheight The height of the clipped image.
X The x coordinates where to place the image on the canvas.
Y The y coordinate where to place the image on the canvas.
width The width of the image to use (stretch or reduce the image).
height The height of the image to use (stretch or reduce the image).

Example -

The below example describes how to draw image in canvas.
<!DOCTYPE html>
<html>
 <body>
    <p>Image to use:</p>
    <img id="bird" src="img/bird.jfif" alt="bird" width="200"
                                                height="150">
    <p>Canvas to fill:</p>
    <canvas id="myCanvas1" width="250" height="180" 
               style="border:1px solid #d3d3d3;">
        Your browser does not support the HTML5 canvas tag.
    </canvas>
	<button onclick="myCanvas1()">Draw image in canvas</button>

    <script>
        function myCanvas1() {
        var c = document.getElementById("myCanvas1");
        var ctx = c.getContext("2d");
        var img = document.getElementById("bird");
        ctx.drawImage(img,10,10);
        } 
     </script>
 </body> 
</html> 

Output -

Before button Click -

Image to use -

bird

Canvas to fill:

Your browser does not support the HTML5 canvas tag.

Browser Support

The following browsers with versions in the table indicates the initial browser version that completely supports the drawimage( ) method -

Method Chrome Edge Firefox Safari Opera
Drawimage( ) Yes 9.0 and above Yes Yes Yes