How to draw existing <img> to canvas

canvas, html, javascript

Solution

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

Problem

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

Original source