How to draw an existing <img> on canvas

I know I can do this with 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 an existing tag on the canvas:

In html:

 <img src='test.png'> 

Why do I want to do this? I want to optimize image loading with pagepeed

+4
source share
5 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

+4
source

Assuming you have id #image , you can use

 var img = document.getElementById("image"); var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context img.onload = function(){ ctx.drawImage(img, 200, 200); // x, y, width, height } 
+1
source

Suppose you have an <img> with an image id. You can get a link to an image using the getElementById method. Something like the following:

 var img = document.getElementById("image"); 

Then use your code above.

+1
source

You can transfer the src image to your new image

 var ctx = getCanvas('testCanvas').getContext('2d'); // get Canvas context var img = new Image(); img.src = document.getElementById('testImage').src; img.onload = function(){ ctx.drawImage(img, 200, 200); // x, y, width, height } 

add id to image element

 <img src='test.png' id="testImage"> 
+1
source

Try

 var canvas=document.getElementById("test"); var ctx=canvas.getContext("2d"); var img=document.getElementById("imgID"); ctx.drawImage(img,10,10); 
+1
source

Source: https://habr.com/ru/post/1491786/


All Articles