Is context.drawImage not displaying the image on the Canvas

suggest change

Make sure your image object is fully loaded before you try to draw it on the canvas with context.drawImage. Otherwise the image will silently fail to display.

In JavaScript, images are not loaded immediately. Instead, images are loaded asynchronously and during the time they take to load JavaScript continues executing any code that follows image.src. This means context.drawImage may be executed with an empty image and therefore will display nothing.

Example making sure the image is fully loaded before trying to draw it with .drawImage

var img=new Image();
img.onload=start;
img.onerror=function(){alert(img.src+' failed');} 
img.src="someImage.png";
function start(){
    // start() is called AFTER the image is fully loaded regardless 
    //     of start's position in the code
}

Example loading multiple images before trying to draw with any of them

There are more full-functioned image loaders, but this example illustrates how to do it

// first image
var img1=new Image();
img1.onload=start;
img1.onerror=function(){alert(img1.src+' failed to load.');};
img1.src="imageOne.png";
// second image
var img2=new Image();
img2.onload=start;
img1.onerror=function(){alert(img2.src+' failed to load.');};
img2.src="imageTwo.png";
//
var imgCount=2;
// start is called every time an image loads
function start(){
    // countdown until all images are loaded
    if(--imgCount>0){return;}
    // All the images are now successfully loaded
    // context.drawImage will successfully draw each one
    context.drawImage(img1,0,0);
    context.drawImage(img2,50,0);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents