To draw an image from a data URL to a canvas using JavaScript, you can follow these steps:
- Get a reference to the canvas element in your HTML.
- Create a new Image object in JavaScript.
- Set the source of the Image object to the data URL.
- Once the image has loaded, use the
drawImage()
method of the canvas context to draw the image onto the canvas.
Here’s a code example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draw Image from Data URL</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
// Get reference to the canvas element
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Create a new Image object
var img = new Image();
// Set the source of the Image object to the data URL
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/AAX+Av7czFnnAAAAAElFTkSuQmCC';
// Once the image has loaded, draw it onto the canvas
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
</script>
</body>
</html>
In this example, replace the data URL (img.src
) with your own data URL.
This code will draw the image onto the canvas as soon as it’s loaded.
Adjust the width, height, and position where you want to draw the image as needed.