Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading