0

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;
                        }
                }
        }
ARI FISHER
  • 343
  • 1
  • 13
  • Please, someone, find a duplicate. This question was silly because of `var` vs `let` – ARI FISHER Nov 22 '20 at 22:09
  • I think https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var is the question – ARI FISHER Nov 22 '20 at 22:12
  • https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example is related too. The current code is better suited for "older" `forEach()`, then `rows` and `tile` would not become a global variable, and the scope would have worked too. – tevemadar Nov 22 '20 at 22:20

1 Answers1

0

Of course, the issue was that toDraw is a non-local variable (it uses var and therefore function scope.) I fixed it by changing it to let.

ARI FISHER
  • 343
  • 1
  • 13