Reputation: 1793
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
Upvotes: 6
Views: 2410
Reputation: 4638
Try
var canvas=document.getElementById("test");
var ctx=canvas.getContext("2d");
var img=document.getElementById("imgID");
ctx.drawImage(img,10,10);
Upvotes: 2
Reputation: 1634
You can give the image src 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 your image element
<img src='test.png' id="testImage">
Upvotes: 1
Reputation: 57
Suppose you have an <img>
tag with id of image. You can obtain the image reference by using the getElementById method. Something like the following:
var img = document.getElementById("image");
Then using your code above.
Upvotes: 1
Reputation: 8005
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
Upvotes: 5
Reputation: 729
assuming that your has the id #image
, you could 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
}
Upvotes: 1