Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw existing <img> to canvas

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

like image 537
Superbiji Avatar asked Jul 17 '13 06:07

Superbiji


People also ask

Can you draw on an image in canvas?

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.

How do I load an image into canvas?

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.

How do I convert a file to canvas?

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.


2 Answers

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

like image 179
Sebastian Avatar answered Oct 03 '22 02:10

Sebastian


Try

var canvas=document.getElementById("test");
var ctx=canvas.getContext("2d");
var img=document.getElementById("imgID");
ctx.drawImage(img,10,10);
like image 26
Arun Bertil Avatar answered Oct 03 '22 02:10

Arun Bertil