0

I am learning JavaScript and came across a problem I am just not able to resolve.

I am loading four images and setting their onLoad to a function called draw. However, draw is called immediately even before the image.src is set. Please see my code below.

HTML Code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="./style.css">
        <title>Canvas: Draw Multiple Images</title>
        <script src="./script.js"></script>
    </head>
    <body>
        <header>
            <h1>Canvas: Learning How to Draw Multiple Images</h1>
            <p>The images are loaded asynchronously. This has to be catered for</p>
        </header>
        <main>
            <canvas id="myCanvas" width="1020" height="1020">
                Your browser doesnot display canvas...
            </canvas>
        </main>
    </body>
</html>

JavaScript Code

var ImagesToLoad = [
    "https://tahititourisme.com/wp-content/uploads/2020/05/Featured-Image-700-x-700-px-1-1.png",
    "https://upload.wikimedia.org/wikipedia/commons/a/a8/Grapefruit%2C_half.jpg",
    "http://www.todaysparent.com/wp-content/uploads/2014/01/1RomasPregnancy-January2014-iStockphoto.jpg",
    "https://media.nature.com/w700/magazine-assets/d41586-017-08492-y/d41586-017-08492-y_15320844.jpg"
];

var images = [];
var canvas, ctx;
var nImagestoLoad = 0;

if (document.readyState === 'loading') {
    document.addEventListener("DOMContentLoaded", myInit);
} else {
    myInit();
}

function myInit() {
    canvas = document.querySelector("#myCanvas");
    ctx = canvas.getContext("2d");

     nImagestoLoad = ImagesToLoad.length; 

    for (var i = 0; i < nImagestoLoad; i++) {
        let img = new Image();
        img.onload = draw();
        images[i] = img;
        //images[i].onLoad = draw();
        img.src = ImagesToLoad[i];
    }
}

function draw() {
    if (--nImagestoLoad > 0) {
        return;
    }

    ctx.drawImage(images[0], 10, 10, 500, 500);
    ctx.drawImage(images[1], 510, 10, 500, 500);
    ctx.drawImage(images[2], 10, 510, 500, 500);
    ctx.drawImage(images[3], 510, 510, 500, 500);

}
Alex
  • 29
  • 4
  • 1
    `draw()` executes the function. Remove the `()` – Andreas Aug 03 '21 at 07:02
  • 1
    `img.onload = draw();` calls draw immediately and sets `img.onload` to the returned value. You need `img.onload = draw;` (in case it's not clear: think about what `img.onload = Math.sqrt(9);` does) –  Aug 03 '21 at 07:02
  • 2
    Duplicate: [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) –  Aug 03 '21 at 07:15

0 Answers0