8

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?

Joe
  • 377
  • 3
  • 5
  • 13

3 Answers3

16

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

letiagoalves
  • 11,224
  • 4
  • 40
  • 66
0
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

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.

Arnau Lacambra
  • 130
  • 1
  • 7