0

Im working on webgl app. I have starsList array and for some reason, when I run this function:

function initTextures() {

        for (i = 0; i < starsList.length; i++) {
            starsList[i].texture = gl.createTexture();
            starsList[i].texture.image = new Image();
            starsList[i].texture.image.onload = function () {
                handleLoadedTexture(starsList[i].texture)
            }
            starsList[i].texture.image.src = starsList[i].name + ".gif"; 
        }   
    }

I got this error:

TypeError: starsList[i] is undefined
handleLoadedTexture(starsList[i].texture)

although starsList[i].texture defined at the first line in the loop.
any ideas why?

LJᛃ
  • 7,655
  • 2
  • 24
  • 35
john
  • 45
  • 10

1 Answers1

0

When your onload callback is called your i is equal to starsList.length.

So starsList[starsList.length] is undefined.

When you declare your callback starsList[i].texture.image.onload = function () { handleLoadedTexture(starsList[i].texture) } it doesn't copy some specific value of starsList. It will just try to find all variables in scope when it been called.

For solution you can bind each onload callback to use specific i

Mike Yermolayev
  • 159
  • 1
  • 11