JS Canvas image will only load once

I am trying to code a canvas drawing algorithm that draws one image for each element in an array. (e. g. [[0,0,0,0], [0,0,0,0]] will produce 2*4 grass textures). But for some reason, the image will only load once. There are no errors and the loop is working correctly, but the image only loads once, according to debugging. I looked at MDN but I can't spot what the issue is. Can someone help?

for (rows in world) {
                for (tile in world[rows]) {
                        var toDraw = {img: new Image(), x: rows * 64, y: tile * 64}
                        toDraw.img.addEventListener('load', function() {
                                ctx.drawImage(toDraw.img, toDraw.x, toDraw.y);
                        }, false);
                        switch(world[rows][tile]) {
                                case 0:
                                        toDraw.img.src = "GrassTexture.png";
                                        break;
                        }
                }
        }


Read more here: https://stackoverflow.com/questions/64959939/js-canvas-image-will-only-load-once

Content Attribution

This content was originally published by ARI FISHER at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: