HTML Canvas - drawImage() Method



The HTML Canvas drawImage() method of Canvas 2D API provides different ways to draw/add an image onto the Canvas element.

Syntax

Following is the syntax of HTML Canvas drawImage() method −

CanvasRenderingContext2D.drawImage(image, sx, sy, s	w, sh, dx, dy, dw, dh);

Parameters

Following is the list of parameters of this method −

S.No Parameter & Description
1

image

An image element which is to be drawn onto the Canvas element by passing as a parameter to the method.

2

sx

x co-ordinate position of the top-left corner of the source image in Canvas.

3

sy

y co-ordinate position of the top-left corner of the source image in Canvas.

4

sw

width of the source image.

5

sh

height of the source image.

6

dx

x co-ordinate position in the destination canvas at which to place the top-left corner of the source image in Canvas.

7

dy

y co-ordinate position in the destination canvas at which to place the top-left corner of the source image in Canvas.

8

dw

width of the image to draw in the destination canvas.

9

dh

height of the image to draw in the destination canvas.

Return value

An image is drawn onto the Canvas element by using the method drawImage() and image object created by the canvas context.

Example

The following example draws an image onto the Canvas element using the method HTML Canvas drawImage() method.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="400" height="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var image = new Image();
      image.onload = function() {
         context.drawImage(image, 50, 50);
      };
      image.src = 'https://www.tutorialspoint.com/html5/images/logo.png';
   </script>
</body>
</html>

Output

The output returned by the image on the webpage as −

HTML Canvas DrawImage Method

Example

The following example draws a partial image onto the Canvas using the parameters of source and destination for the method drawImage().

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var image = new Image();
      image.onload = function() {
         context.drawImage(image, 10, 10, 150, 100, 25, 25, 150, 100);;
      };
      image.src = 'https://www.tutorialspoint.com/html5/images/logo.png';
   </script>
</body>
</html>

Output

The output returned by the image on the webpage as −

HTML Canvas DrawImage Method
html_canvas_images.htm
Advertisements