Pulling in textures to enhance the rendering for webgl

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?

Answer №1

The issue lies in the scope of the counter variable you are using. In your loop, the counter variable increments and the loop exits once it reaches or exceeds Planets.length. By the time the callback is triggered, the loop has already ended and i remains at Planets.length.

To address this, you can employ an IIFE (immediately invoked function expression) to create a localized version of i as shown below:

for(var i = 0; i < Planets.length; i++)
{
    TextureName[i] = gl.createTexture();
    TextureName[i].image = new Image();
    TextureName[i].image.onload = (function (index) {
        return function () { handleLoadedTexture(TextureName[index]) }
    })(i);
    TextureName[i].image.src = Planets[i].name+".jpg";
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve specific values from the HTTP response header string?

When trying to authenticate against a proxy server, it is necessary to analyze the proxy-authenticate header string after the initial HTTP request to retrieve the important values. The response headers typically contain information like this, { 'con ...

Steps for adjusting the structure of an array of objects according to the ParentID

I need to reorganize an array of objects based on a field called ParentID. Here is an example dataset: var JsonVal = "data": { "Factorid": 197325, "orders": [ { ...

Does modifying data from an AngularJS service update the original data within the service?

Accidentally, I managed to create something that works but feels like it shouldn't! Essentially, I have a JSON data with a list of items that can be selected by the user, modified, and then saved. Here is a simplified version of the code: app.service ...

Firebase Cloud Functions streamline lengthy tasks by avoiding the risk of hitting a time threshold

Upon uploading videos to firebase storage, I am faced with the task of transcoding webm files to mp4 format. While I have a functional code demo available here, the issue arises when dealing with large video files. The conversion process often exceeds the ...

Tips for eliminating unnecessary or duplicate dependencies in package.json files

While I am aware that this question has been asked previously on Stack Overflow, I have found that depcheck does not work effectively for me. It provides numerous false alerts and requires specific configuration for libraries like babel, eslint, etc. How ...

A guide on utilizing express.js to retrieve and display the output of a mySql query

I am facing an issue with getting the results of my simple SELECT command into the index.js file. I want to store all the records in an array, but when I try to do so, I always end up with undefined values. Interestingly, if I print the results in the data ...

Automatically fill in form fields with data from a JSON file as soon as the user enters a value

How can I retrieve the bank name, branch, city, and district from a JSON array? Below is the contents of my results.json file: { "ifsc": [{ "ifsc": "PUNB0000100", "bank": "PUNJAB NATIONAL BANK", "city": "ABOHAR ...

Unexpected JSONP Parsing Issue Despite Correct JSON Data

I've implemented a Cross Domain AJAX request using JSONP, and it's working fine with CORS. However, I'm facing an issue with JSONP. I've checked other threads but couldn't find a solution for my case. Below is the code snippet: ...

Populating a C array with pointers

In my current homework assignment, I am tasked with populating an array with random numbers without any repeats. The catch is that I cannot use the [i] identifier and must instead utilize pointers. To experiment with how pointers work, I initially started ...

What could be the reason for the malfunctioning transition effect in my slider animation?

Having trouble getting my slider animation to work. I've tried different CSS styles but the slide transition is not functioning as expected. When one of the buttons is clicked, I want the slide to change from right to left or left to right. Can anyone ...

How come attempting to read a nonexistent document from Firestore results in an uncaught promise?

I've been struggling to read and display data from Firestore, but I keep seeing error messages in the console. Encountered (in promise) a TypeError: Unable to read properties of undefined (reading 'ex') Encountered (in promise) a TypeError ...

"Transforming a query into a JSON array - a step-by-step

My query generates the following output: { key:1,label:"R. Bulan"} { key:2,label:"R. Bintang"} { key:3,label:"R. Akasia"} { key:4,label:"R. Guest Room"} This is my SQL query: select '{ '||'key:'||IDMEETINGROOM||''||',l ...

Synchronize scrolling between two elements to create a dynamic user experience

I'm currently facing an unusual situation. Take a look at the following image: Link to image So, I have this ruler positioned at the top. To prevent it from scrolling off when I vertically scroll the content, I placed it outside the scrolling contai ...

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Issue with Three.js SubdivisionModifier leading to a null error

Currently, I am working with the Three.js library and trying to implement a Subdivision Modifier on a model. I have been successful in loading a model and applying a subdivision modifier to a CubeGeometry. The code functions properly when the specific line ...

Having difficulty populating the token in the h-captcha-response innerHTML and g-recaptcha-response innerHTML

I am attempting to use 2captcha along with Selenium and Python to bypass an Hcaptcha. After receiving my 2captcha token, I attempt to input it into the textareas labeled 'h-captcha-response' and 'g-captcha-response'. However, this app ...

Could someone clarify the code for me? I'm struggling to grasp the meaning behind using !toggle in the onClick function and ? in the return statement

I'm having trouble understanding this code. I don't know why there is !toggle inside onClick and ? inside return. As a beginner, this code is confusing to me. Any help in explaining this code would be greatly appreciated. import {useState} from ...

How to create an array of objects in Angular 2

Can someone please help me understand how to set up an array of objects so that I can add items to it later on? Here's what I currently have: tab: [{tel:number, name:String}]; ...

Ways to update or incorporate new data within JavaScript

I'm currently experimenting with ways to incorporate additional text or even AdSense into what I believe is a .js file. There's an operational lightbox feature with a descriptive caption at the bottom, and that caption is what I want to modify. ...

Issue with AngularJS form not binding to $http request

<form novalidate class="form-horizontal"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="text-capitalize"> </ ...