javascriptdomdom-eventshtml5-canvasdrawimage

Why are my canvas images not loading/rendering in proper sequence or as expected with image.onload?


I am trying have one image load onto an HTML canvas and then another image load on top of that image. However, I am getting the following behaviors from each browser:

Chrome:

1st execution - Only the background image (backImage) seems to be present however for a millisecond during load, the character image (charImage) is visible behind the background image.

Refreshes - Sometimes the character image appears in front of the background image and then other times it is vice versa. There is no pattern to this behavior.

NOTE: When the code is inserted directly into the browser console, it behaves as expected. (background image behind, character image in front).

Firefox:

1st execution - Only the background image (backImage) seems to be present however for a millisecond during load, the character image (charImage) is visible behind the background image.

Refreshes - Suddenly after a refresh (and all following refreshes), it is behaving as expected (background image behind, character image in front).

I have seen some prior posts about utilizing the .onload event however I am utilizing it here and still having what I assume to be timing issues. Any suggestions are greatly appreciated. I am very new to coding in general.

TIA!

// Create Canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

// Background Image
var backImage = new Image();
backImage.onload = function(){
    ctx.drawImage(backImage,0,0);
};
backImage.src = "Images/Flowers.jpg";

// Character Image
var charImage = new Image();
charImage.onload = function(){
    ctx.drawImage(charImage,0,0,50,50);
};
charImage.src = "Images/Butterfly.jpg";

Solution

  • Move the drawing of the second image into the onload event handler for the background image.

    let backImage = new Image();
    backImage.onload = function() {
        ctx.drawImage(backImage, 0, 0);
        let charImage = new Image();
        charImage.onload = function() {
            ctx.drawImage(charImage, 0, 0, 50, 50);
        };
        charImage.src = "Images/Butterfly.jpg";
    };
    backImage.src = "Images/Flowers.jpg";