How do you Draw an Image From Data URL to A HTML Canvas?


Data URLs are a way to represent an image file in a text format. This makes it easy to transfer data between applications, as well as store the image in memory without having to write it out to disk. Drawing an image from a Data URL onto a HTML canvas is relatively straightforward and can be done with only a few lines of code.

The process involves creating an Image object and setting its source attribute to the Data URL string before drawing it on the canvas using the drawImage() method. This article will provide step-by-step instructions for how to draw an image from data URL onto a HTML canvas.

Using drawImage() in Canvas

A canvas picture or video is displayed using HTML5's drawImage() method. You may use this feature to display the entire image or only a portion of it. But before the image can be loaded farther on canvas, it must first be loaded.

Syntax

Following is the syntax for drawImage() -

context.drawImage(img,x,y);

Consider the following examples to get a better idea of how to draw an image from a data URL onto an HTML canvas

Example

In the following example, we are running the script to draw an image from the URL onto the canvas.

<!DOCTYPE html>
<html>
   <body>
      <canvas id="tutorial"></canvas>
      <script>
         var c = document.getElementById("tutorial");
         var ctx = c.getContext("2d");
         var image = new Image();
         image.onload = function() {
            ctx.drawImage(image, 0, 0);
         };
         image.src = 'https://www.tutorialspoint.com/images/logo.png';
      </script>
   </body>
</html>

When the script gets executed, it will generate an output consisting of an image that was drawn on the canvas obtained from the URL provided in the script.

Example

Following is another example, here we are displaying partial image from a source URL on the canvas

<!DOCTYPE html>
<html>
   <body>
      <style>
         canvas{
            border : 2px solid #82E0AA ;
         }
      </style>
      <canvas id='tutorial' width=500 height=500></canvas>
      <script>
         var canvas = document.getElementById('tutorial');
         var context = canvas.getContext('2d');
         var image = new Image();
         image.onload = () => {
            context.imageSmoothingEnabled = false;
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.drawImage(image, 30, 40, 50, 50, 150, 220, 200, 200);
         };
         image.src = 'https://www.tutorialspoint.com/images/logo.png';
      </script>
   </body>
</html>

On running the above script, the output window will pop up, displaying the image on the webpage drawn on the canvas obtained from the URL.

Updated on: 20-Apr-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements