My current challenge involves the process of loading textures in webgl. I have a collection of planets with unique names and values, each corresponding to a texture named sun.jpg, mercury.jpg, etc. By constructing the name string using Planets[i].name+".jpg"
, I aim to retrieve the texture's name.
An error message is displayed as follows: Uncaught TypeError: Cannot read property 'image' of undefinedSpheredPlanetsGL.js:138 handleLoadedTextureSpheredPlanetsGL.js:179 TextureName.(anonymous function).image.onload
The TextureName array is set up in the following manner:
var TextureName = [];
function setBufferName()
{
for(var i = 0; i < Planets.length; i++)
{
TextureName[i] = {name: Planets[i].name+"TextureName"};
}
}
The initialization of textures occurs as shown below to ensure correct references between "sunTextureName" and "sun.jpg" for all planets:
function initTexture()
{
for(var i = 0; i < Planets.length; i++)
{
TextureName[i] = gl.createTexture();
TextureName[i].image = new Image();
TextureName[i].image.onload = function ()
{
handleLoadedTexture(TextureName[i]);
}
TextureName[i].image.src = Planets[i].name+".jpg";
}
}
The issue arises when calling "handleLoadedTexture(TextureName[i])", which leads to confusion regarding the following function:
function handleLoadedTexture(texture)
{
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
gl.generateMipmap(gl.TEXTURE_2D);
gl.bindTexture(gl.TEXTURE_2D, null);
}
The exact line causing an error is
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
. Despite passing the variable correctly, it seems unable to reference the array contents.
I am seeking assistance to resolve this issue. Any suggestions?