Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas drawImage() not working

This Javascript code draw part of the image on the canvas:

var img = document.getElementById('img');
var canvas = document.getElementById('can');
//canvas.width = img.width;
//canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

But when I uncomment the middle lines to set the canvas width and height, the drawImage() does not work. What should I check in order to find the problem?

like image 618
Joe Avatar asked Sep 17 '13 13:09

Joe


1 Answers

You need to wait for the browser to load the image.

Use onload event if image was not yet loaded and change your 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) { //check if image was already loaded by the browser
   callback(img);
}else {
   img.onload = callback;
}

See this working demo

like image 199
letiagoalves Avatar answered Oct 11 '22 14:10

letiagoalves