You need to wait for the browser to load the image .
Use the onload if the image is not already loaded and change the code to something like this:
var img = document.getElementById('img'); var canvas = document.getElementById('can'); var ctx = canvas.getContext("2d"); var callback = function(image) { if(!image) image = this; canvas.width = img.width; canvas.height = img.height; ctx.drawImage(image, 0, 0); } if(img.complete) {
See this working demo.
letiagoalves
source share