Data URLs are a way of representing image files in text format. This makes it easy to transfer data between applications and allows images to be stored in memory without writing them to disk. Drawing an image on an HTML canvas using a Data URL is relatively simple and can be done with just 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.
Use HTML5's drawImage() method to display canvas images or videos. You can use this feature to display the entire image or only part of it. But before the image can be loaded further on the canvas, it must first be loaded.
The following is the syntax of drawImage()-
context.drawImage(img,x,y);
Consider the following example to better understand how to draw an image from a data URL to an HTML canvas
In the example below, we are running a script that draws an image from a URL to 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 is executed, it will generate an output containing the image drawn on the canvas obtained from the URL provided by the script.
Below is another example where we display a partial image from the 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.
The above is the detailed content of How to draw Data URL into HTML canvas?. For more information, please follow other related articles on the PHP Chinese website!