8
votes

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?

3
Why do you think that uncommenting produced the problem?Joe

3 Answers

16
votes

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

0
votes
var img = document.getElementById('img');

Try naming the variable something else. Also make sure some image is loaded.

Try my fiddle http://jsfiddle.net/aliasm2k/tAum2/ for more ideas

0
votes

The width and height image attributes aren't set until the image is loaded, so i propose you to put your code in onLoad() image event.