Open In App

HTML canvas drawImage() Method

Improve
Improve
Like Article
Like
Save
Share
Report

In HTML5, canvas drawImage() function is used to display an image or video on canvas. This function can be used to display the whole image or just a small part of the image. But, image has to be loaded first to load it further on canvas. 

Syntax: 

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

Parameter Values:  

  • img: It indicates the image or video to draw on canvas.
  • x: It indicates the x-coordinate where image has to be placed.
  • y: It indicates the y-coordinate where image has to be placed.
  • swidth: It is optional parameter and indicates the width of the clipped image.
  • sheight: It is optional parameter and indicates the height of the clipped image.
  • sx: It is optional parameter and indicates x-coordinate where to start the clipping.
  • sy: It is optional parameter and indicates y-coordinate where to start the clipping.
  • width: It is optional parameter and indicates the width of the image to use.
  • height: It is optional parameter and indicates the height of the image to use.

Example:  

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML | canvas drawImage() Method
    </title>
</head>
  
<body>
      
<p>Image:</p>
  
    <img id="GFG" width="480" height="240" 
        src="canvas drawImage.png" alt="The Scream" />
  
      
<p>Canvas:</p>
  
  
    <canvas id="myGFGCanvas" width="520" height="300"
            style="border: 1px solid #d3d3d3;">
        Your browser is not supported 
        for HTML5 canvas tag.
    </canvas>
  
    <script>
        window.onload = function () {
            var c = document.getElementById("myGFGCanvas");
            var ctx = c.getContext("2d");
            var img = document.getElementById("GFG");
            ctx.drawImage(img, 20, 20);
        };
    </script>
</body>
  
</html>


Output: 

 



Last Updated : 12 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads