HTML Canvas - Adding Images



The best feature of the Canvas element is it can accept images and use them. Canvas element accepts all external image files to display on the webpage and we can use the images produced by other Canvas elements which are available on the same webpage. Importing an image to the Canvas is a two-step process

  • Retrieve the image using any of the available options.

  • Draw the image onto the canvas element using the drawImage() function.

Retrieving images

The Canvas API can use any of the following data types as an image source.

  • HTMLImageElement − These images are created using Image() constructor or the <img> tag of HTML.

  • SVGImageElement − The images are generally embedded using the <image> element.

  • HTMLVideoElement − It uses HTML <video> element as the image source and grabs the current video frame and uses it as the required image.

  • HTMLCanvasElement − We can use another Canvas element that is available on the same webpage as the image source. To retrieve images onto the Canvas element and use them, there are six possible ways, and each is mentioned below.

Images from the same page

We can obtain all the images available on the pages using the DOM model. To find all the available images, document.images collection must be accessed. To use one of the available images, we can use document.getElementsByTagName() method or document.getElementById() method if we know the ID of that specific image.

Images from other domains

To retrieve an image that is available in the other domain, we will use the tag and call the image to the Canvas element using the drawImage() function. Make sure the image is transferrable, or else the canvas may get tainted.

Images using other Canvas elements

When we retrieved the images available on same page using document.getElementsByTagName() or document.getElementById() method, we can use the same to retrieve images from other Canvas elements also. To achieve this, we must make sure the source canvas is already drawn before it is used by the target canvas.

Embedding the image using URL

To include an image to the canvas, we can directly add the image URL to the code and access it. The main advantages of using URL are that the image can be accessed very fast than other methods as it does not have to get server access again and make it portable to other locations. If the image is not perfectly accessed by URL, it might not be displayed on canvas. A simple code snippet to access the image using the URL is given below

// Creating an image element
var image = new Image();
// Accessing the image using URL
image.src = 'https://www.tutorialspoint.com/scripts/img/logo-footer.png';

Generate frames from video

We can get image frames from the video using <video> element. For example, if we have a video element having id as smallvideo, we can get frames from it and use it as an image. A small code snippet is given below to demonstrate image retrieval

// function to get image frame
function frameFromVideo() {
   var canvas = document.getElementById('canvas');
   var context = canvas.getContext('2d');
   return document.getElementById('smallvideo');
}

Building image from scratch

We can use image() constructor to create the image and access it using its path. The image starts loading after the image path is fed to the constructor. A small code is given below to show how an image is built from scratch using the source path.

// Create new img element
var image = new Image();
// to avoid exceptions
image.addEventListener('load', function() {
   // add draw image code statements here
}, false);
// give image source path
image.src = 'imageaddress.png';

Draw images

HTML5 Canvas element is equipped with a default method to draw images on the canvas. The method is given below

S.No Method & Description
1

drawImage()

This method draws the image onto the canvas element. The method takes three types of input parameters and is given accordingly.

2

drawImage(image, x, y)

This method takes the image as the first parameter and draws it at the point ( x, y) on Canvas.

3

drawImage(image, x, y, width, height)

This method draws the image given as a parameter on the canvas at the point (x, y) with the given width and height. This method is generally used for scaling the image.

4

drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

This method contains source points and destination points with width and height for the source as well as the destination. This method is used for slicing the image.

Example

Following example code implements how an image is drawn into the Canvas element.

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Images</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body onload="image();">
      <canvas id="canvas" width="450" height="200" style="border: 1px solid black;"></canvas>
      <script>
         function image() {
            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 code renders the image onto canvas and is shown below

Draw Images

Scaling and Slicing

Image scaling is very useful when there is a need to contain the space of canvas so that other shapes or graphics can be constructed inside the Canvas element. Scaling may cause image blurriness, so the parameters should be given correctly. The method which helps us to perform scaling on the Canvas image is

drawImage( image, x, y, width, height);

Example for scaling

Following example demonstrates how scaling can be performed on the same image by varying width and height parameters . The implementation code is given below

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

Output

The output for the above code is

Example for Scaling

Slicing helps us to take a part of the image and paste it on the Canvas element. The first four parameters after the image parameter denotes the size of the image to be sliced and the other parameters denotes where it should be pasted into the Canvas with a specified width and height. The method used to achieve the slicing is

drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);

Example for slicing

Following example shows how an image is sliced. The implementation code is given below

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

Output

The output for the following code is

Example for Slicing
Advertisements