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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With