Why won't my loop with THREE.ImageUtils.loadTexture function load the textures properly?

I've implemented code from three.js examples successfully in a different location, but it's not working within a loop.

There seems to be something I'm overlooking as this is my third attempt at the code with no success.
It appears that the callback function is firing prematurely, resulting in an empty object.

The specific error message I'm encountering is "Uncaught TypeError: Cannot read property 'image' of undefined"... typical.

var images = 
[ '01.jpg',
  '02.jpg',
  '03.jpg',
  '04.jpg',
  '05.jpg'  ];

function loadImages(){

 var callbackPainting = function(i) {

    var texture = texturePainting[i];
    console.log(texture); // this returns "undefined"
    var image = texture.image;

    var geometry = new THREE.PlaneBufferGeometry( 100, 100 );
    var mesh = new THREE.Mesh( geometry, materialPainting[i] );

    addPainting( scene, mesh );

    function addPainting( zscene, zmesh ) {

      zmesh.scale.x = image.width / 100;
      zmesh.scale.y = image.height / 100;
      // I know this makes the images in the same location. Overlook
      zmesh.position.set(0,0,0);
      zscene.add( zmesh );

    }


  };
  var texturePainting = {}
  var materialPainting = {}
  for(i in images){
    image = "images/" + images[i];
    texturePainting[i] = THREE.ImageUtils.loadTexture( image, THREE.UVMapping, callbackPainting(i) );
    texturePainting[i].minFilter = THREE.LinearFilter;
    materialPainting[i] = new THREE.MeshBasicMaterial( { map: texturePainting[i] } );
  }

}

Answer №1

Within the code snippet

texturePainting[i] = THREE.ImageUtils.loadTexture( image, THREE.UVMapping, callbackPainting(i) );
, the function callbackPainting() is invoked immediately with the argument i.

To refactor callbackPainting() so that it returns a function and preserves each passed value of

i</code within a closure, you can modify it as follows:</p>

<pre><code>var callbackPainting = function(i) {

  return function() {

    var texture = texturePainting[i];
    ...

  }

};

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

eliminate the gap in the MUI Accordion when it is expanded

How can I prevent the Accordion MUI component from moving and applying top and bottom margins to summary elements in expanded mode? I added the following code to the summary element but it doesn't seem to be working. Any suggestions on how to fix this ...

Leveraging material elements in React applications

I have been studying the guide on Material UI Beta for react and I am interested in creating a simple component using the Drawer element. Here is an example code from the official documentation that demonstrates how to build such a Component. import React ...

Exploring the integration of dynamic URLs in Nuxt.js using DRF

After receiving guidance on integrating information from DRF into Nuxt.js, I find myself eager to learn more. I followed the basic instructions but still struggle to grasp the concept. Can anyone offer a solution to this issue? I am particularly intereste ...

Removing values from localStorage in Angular upon closing the application

As I store the Session user in a $localStorage, it poses a challenge for me since my system caters to users in the marketing industry who may not always use their own personal computers every time they access the application. If a user forgets to log out ...

Overlaying images on top of text

Is there a way to overlay an image on text, like a pattern image? Similar to applying color with a hex value in CSS: color: #ffffff; Any ideas on how this can be achieved? I want to have a pattern over text. https://i.sstatic.net/JaNZU.jpg Appreciate ...

Using Javascript to refresh an image and update a class within a DIV when another DIV is clicked

I have a code that is quite lengthy to share here, so I've created a demo on JSFiddle: http://jsfiddle.net/Emily92/5b72k225/ This particular code takes a random image and divides it into multiple sections based on the class applied to the div contain ...

How to retrieve distinct items from an array using Javascript

If I have the following array of objects: const arr = [{ id: 'A', version: 0, name: 'first' }, { id: 'A', version: 1, name: 'first' }, { id: 'B', version: 0, name: 'second&apo ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli: <img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto"> The image has a Base64 url named imgUrl. My intention is to set the image source using the ...

Top technique for mirroring a website

Recently, I created a directory for a client's website. The site is fully operational, but the client would like a replicated version for testing and learning purposes. To create a full replica of his website, it will require hours of work to change ...

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

Adjusting the size of a Vue component on the fly

I'm struggling to find a way to dynamically adjust the width of a component. The component I am working with is called 'vue-burger-menu' -> https://github.com/mbj36/vue-burger-menu. To set the width, you need to assign a number to the p ...

Tips for structuring dependencies within an Angular module

When developing my angular application, I implement the application component segmentation logic by organizing my folders in the following structure: app.module.js app.config.js components ---- core -------- core.module.js -------- etc... ---- component1 ...

Having trouble interpreting JSON with Jquery

I am attempting to implement autosuggestion using Solr in conjunction with jQuery. Below is the code I have written for this purpose: $(function() { $( "#artist" ).autocomplete({ source: function( request, response ) { $.ajax({ ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

What is the solution for resolving AngularJS URL encoding?

Currently, my AngularJS app utilizes a component known as navbar to house the searchbar along with a search() function. $scope.search = function (keyword) { console.log(keyword); $state.go('main', { keyword: keyword }, ...

.then() failing to wait for completion of all promises

Currently, I am loading multiple gltf models using an async function. After that, I go through the results using .then() and add the models to my scene. However, everything works perfectly fine until I decide to remove one of the models from the source. Sp ...

Differences between Vue.js onMounted and watching refsVue.js offers

When it comes to calling a function that requires an HTMLElement as an argument, the element in question is rendered within my page template and therefore I need to ensure it is actually in the DOM before making the call. Two potential methods for waiting ...

How do you modify the SVG viewport using code?

I am looking to create a feature that allows all images inside an SVG object to be moved. My plan is to use JavaScript, and possibly jQuery, to handle mouse events (down, move, up) in order to change the viewport of the SVG. However, I am currently facing ...

Is it possible to use a variable from a popup window's JavaScript to call a jQuery function in the parent window?

Is there a way to use JavaScript in a popup window to call a function from the parent window that contains jQuery? Are there any straightforward examples available for reference? ...