Drawing an image from a data URL to a HTML5 canvas

When working with HTML5 Canvas, you can draw images from data URLs (base64-encoded images) directly onto the canvas. A data URL contains image data encoded as a string, eliminating the need for external image files. This technique is useful for dynamically generated images or when you need to display images stored as base64 strings.

Syntax

Following is the basic syntax for creating an image from a data URL −

var myImg = new Image();
myImg.src = dataURL;

Following is the syntax for drawing the image onto the canvas −

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

The drawImage() Method

The drawImage() method draws an image, canvas, or video onto the canvas. It can also draw parts of an image and resize the image during the drawing process. The method requires the image to be fully loaded before it can be drawn, which is why we use the onload event.

Basic Example

Following example demonstrates how to draw an image from a data URL to a canvas −

<!DOCTYPE html>
<html>
<head>
   <title>Draw Image from Data URL</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <h2>Canvas with Data URL Image</h2>
   <canvas id="myCanvas" width="300" height="200" style="border: 1px solid #000;"></canvas>
   
   <script>
      // Get canvas and context
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      
      // Sample data URL (red square)
      var dataURL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==';
      
      // Create image object
      var myImg = new Image();
      
      // Set onload event before setting src
      myImg.onload = function() {
         context.drawImage(myImg, 50, 50, 100, 100);
         context.fillStyle = 'blue';
         context.font = '16px Arial';
         context.fillText('Image drawn from Data URL', 10, 30);
      };
      
      // Set the data URL source
      myImg.src = dataURL;
   </script>
</body>
</html>

The canvas displays a small image drawn from the data URL along with descriptive text.

Loading Sequence Best Practice

The proper sequence for loading an image from a data URL is crucial for reliable execution −

  1. Create the Image object
  2. Set the onload event handler
  3. Set the src property with the data URL

Example − Complete Loading Sequence

<!DOCTYPE html>
<html>
<head>
   <title>Data URL Loading Sequence</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <h2>Proper Loading Sequence</h2>
   <canvas id="sequenceCanvas" width="400" height="250" style="border: 1px solid #ccc;"></canvas>
   <button onclick="loadImage()">Load Image</button>
   
   <script>
      function loadImage() {
         var canvas = document.getElementById('sequenceCanvas');
         var context = canvas.getContext('2d');
         
         // Clear canvas
         context.clearRect(0, 0, canvas.width, canvas.height);
         
         // Sample base64 data URL (small blue rectangle)
         var dataURL = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cmVjdCB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIGZpbGw9IiMwMDc3ZmYiLz4KPC9zdmc+';
         
         // Step 1: Create the Image object
         var imageObj = new Image();
         
         // Step 2: Set the onload event handler
         imageObj.onload = function() {
            // Draw the image at different positions and sizes
            context.drawImage(imageObj, 20, 20);           // Original size
            context.drawImage(imageObj, 80, 20, 60, 60);   // Scaled up
            context.drawImage(imageObj, 160, 20, 30, 30);  // Scaled down
            
            // Add labels
            context.fillStyle = 'black';
            context.font = '12px Arial';
            context.fillText('Original', 20, 75);
            context.fillText('Scaled Up', 80, 95);
            context.fillText('Scaled Down', 160, 65);
         };
         
         // Step 3: Set the src property (this triggers loading)
         imageObj.src = dataURL;
      }
   </script>
</body>
</html>

Clicking the "Load Image" button demonstrates drawing the same data URL image at different sizes and positions.

Handling Large Data URLs

When working with larger data URLs, you might want to add error handling and loading indicators.

Example − With Error Handling

<!DOCTYPE html>
<html>
<head>
   <title>Data URL with Error Handling</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <h2>Data URL with Error Handling</h2>
   <canvas id="errorCanvas" width="350" height="200" style="border: 1px solid #999;"></canvas>
   <p id="status">Ready to load image...</p>
   <button onclick="loadWithErrorHandling()">Load Image</button>
   
   <script>
      function loadWithErrorHandling() {
         var canvas = document.getElementById('errorCanvas');
         var context = canvas.getContext('2d');
         var status = document.getElementById('status');
         
         // Clear canvas
         context.clearRect(0, 0, canvas.width, canvas.height);
         status.textContent = 'Loading image...';
         
         // Sample data URL (green circle SVG)
         var dataURL = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAiIGhlaWdodD0iODAiIHZpZXdCb3g9IjAgMCA4MCA4MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSI0MCIgY3k9IjQwIiByPSI0MCIgZmlsbD0iIzAwYmI2NiIvPgo8L3N2Zz4K';
         
         var imageObj = new Image();
         
         // Success handler
         imageObj.onload = function() {
            context.drawImage(imageObj, 50, 50);
            status.textContent = 'Image loaded successfully!';
            status.style.color = 'green';
         };
         
         // Error handler
         imageObj.onerror = function() {
            status.textContent = 'Failed to load image from data URL';
            status.style.color = 'red';
         };
         
         imageObj.src = dataURL;
      }
   </script>
</body>
</html>

This example includes both success and error handling, providing feedback to the user about the loading status.

Data URL to Canvas Process Data URL (base64) Image Object (new Image()) Canvas (drawImage()) 1. Create Image 2. Set onload handler 3. Draw to canvas imageObj.src = dataURL triggers the loading process

Common Use Cases

Drawing images from data URLs to canvas is commonly used for −

  • Dynamic image generation − Creating images programmatically and displaying them immediately.

  • Image editing applications − Loading user-uploaded images converted to base64 for manipulation.

  • Offline applications − Storing images as data URLs to work without network access.

  • Image processing − Converting between different formats or applying filters.

Conclusion

To draw an image from a data URL to an HTML5 canvas, create an Image object, set its onload event handler to call drawImage(), and then assign the data URL to the src property. Always set the onload handler before setting the src to ensure proper loading sequence and reliable execution across all browsers.

Updated on: 2026-03-16T21:38:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements