Canvas drawImage () not working

This Javascript code painted 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 width and height of the canvas, drawImage () does not work. What should I check to find the problem?

+7
javascript html5 canvas
source share
3 answers

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

See this working demo.

+15
source share
 var img = document.getElementById('img'); 

Try assigning the variable something else. Also make sure some image is uploaded.

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

0
source share

Width and height image attributes are not set until the image is loaded, so I suggest you put your code in the onLoad () image event.

0
source share

All Articles