There is much to explain. I checked the code below and got it working, but I just used one image again and again. We hope this works when combined with your code. Put the code below, instead of your for loops (i.e. after var height and before the getImageNameFromRand function).
Firstly, your code defines all vars in the global namespace, so img var is replaced every time through the source loop, as well as its src and onload function, etc. In addition, x and y, which increase the for loops, get a link through a closure in the onload function, but since they only increase during the outer loop (not in the onload function), they are both set to their final values during the onload call (final values when starting the source loop).
Also, try adding all of your script to an anonymous function, for example (function () {YOUR CODE HERE}) (). This way you will not add to the global namespace with local vars, and onload will have what it needs because of the closure. I tested everything in an anonymous function and it worked for me.
Hope I copied and put it all right. Please comment if it is turned off. Good luck !!!
//Copy this code in place of your original "for" loop: var imgs = []; var imgIndex = 0; for (var x = 0; x < width; x++){ for(var y = 0; y < height; y++){ var rand = Math.floor(Math.random() * 11); var texLoc = getImageNameFromRand(rand, y, height); imgs[imgIndex] = new Image(); imgs[imgIndex].onload = (function () { var thisX = x * 16; var thisY = y * 16; return function () { ctx.drawImage(this, thisX, thisY); }; }()); imgs[imgIndex].src = texLoc; imgIndex += 1; } }
source share