I know I can do this using javascript:
var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context
var img = new Image();
img.src = 'test.png';
img.onload = function(){
ctx.drawImage(img, 200, 200); // x, y, width, height
}
But how to draw existing tag to canvas:
In html:
<img src='test.png'>
Why I want to do this? I want to optimize image loading using pagespeed
Definition and Usage. The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.
Importing images into a canvas is basically a two step process: Get a reference to an HTMLImageElement object or to another canvas element as a source. It is also possible to use images by providing a URL. Draw the image on the canvas using the drawImage() function.
toDataURL( ) ; / / This method saves graphics in png document. getElementById('cimg'). src = imgurl; // This will set img src to dataurl(png) so that it can be saved as image. In this way, we can save canvas data to file in HTML5.
The very first google hit for your question is promising:
var c=document.getElementById("testCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("existingHTMLImageElementId");
ctx.drawImage(img,10,10);
See w3Schools
Try
var canvas=document.getElementById("test");
var ctx=canvas.getContext("2d");
var img=document.getElementById("imgID");
ctx.drawImage(img,10,10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With