Ensure that the texture is loaded in a class before moving forward

Explaining my issue with a simple example, I find it easy to use await async in functions to ensure textures are loaded before moving on with the program. However, when working with classes for a cleaner program structure, I am unsure how to make the constructor wait until the texture is loaded before calling the subsequent function.

//within my three.js init function
var sphereObject = new Sphere(100, texture);
var sphere = this.sphereObject.sphere;
scene.add(sphere); 
//------------------------

class Sphere{
  constructor(radius, preloadedtex){
 
    //this.material = this.doSomething(preloadedtex); //this works fine

    const loader = new THREE.TextureLoader();
    loader.load("grass.png", function(texture){
      this.material = this.doSomething(texture);
    });    
    const geometry = new THREE.SphereGeometry( radius, 128, 64 );
    this.sphere = new THREE.Mesh( geometry, this.material); 

  }

  doSomething(texture){
    //perform additional operations with the texture before returning a material

    return material;
  }

}

Answer №1

The TextureLoader class in Three.js has a built-in onLoad callback function that can be used as the second argument of the .load() method. This information is sourced directly from the official documentation available here:

const loader = new THREE.TextureLoader();

// Load a resource
loader.load(
    // Resource URL
    'textures/land_ocean_ice_cloud_2048.jpg',

    // onLoad callback function
    function ( texture ) {
        // In this example, we create a material using the loaded texture
        const material = new THREE.MeshBasicMaterial( {
            map: texture
         } );
    },

    // onProgress callback is currently not supported
    undefined,

    // onError callback function
    function ( err ) {
        console.error( 'An error occurred.' );
    }
);

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

The options in the dropdown menu vanish when interacting with a jQuery feature that relies on

Recently, I have found AJAX, JSON, and jQuery to be indispensable tools in my coding endeavors. The application I am working on is a replacement for a flawed one, and it is coming along nicely. Despite making progress with the AJAX method, I have encounte ...

Switching the default z-index for child elements within an HTML container

According to the specification, elements are typically drawn "in tree order" for in-flow, non-positioned elements of similar block level or float status and identical z-index. This means that elements declared last in the HTML markup appear on top. But wha ...

I'm baffled as to why this code isn't functioning properly

My current script seems to be malfunctioning for some reason. I'm using a combination of express, socket.io, jade, and node.js in this setup. Below is the script I am working with: var socket = io.connect(); function addMessage(msg) { var currentDa ...

What is the best way to bundle a node module with the choice of adding submodules?

I am in the process of developing a JavaScript library that consists of a central core module and multiple optional submodules that enhance the functionalities of the core module. This library is specifically designed for the browser environment, utilizing ...

Step-by-Step Guide on Retrieving Filtered Data using React Context API

Currently, I am in the process of developing a dashboard application using React.js, React Context API, and ApexCharts. The app will visualize a 1000-length JSON data on 7-8 different charts, along with 6-7 variable filters. Overview of the App Structure: ...

Accessing AngularJS variable scope outside of a function

Utilizing a socket, I am fetching data into an angularJS controller. $rootScope.list1= ''; socket.emit('ticker', symbol); socket.on('quote', function(data) { $rootScope.list1 = angular.fromJson(data.substring(3)); //I can ...

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

Initializing MongoDB server instance created by NodeJS using npm installation

I've recently installed mongodb on my OSX machine by running the command npm install mongodb in the myapp/node_modules directory while using node.js. However, I'm a bit confused because the mongodb official documentation states that to start mong ...

What is the best way to sort an array based on a person's name?

I have a list of different groups and their members: [ { "label": "Group A", "fields": [ { "value": "color1", "name": "Mike" }, { &quo ...

Vue.js does not display HTML properly within the vue-swal component

I'm currently working on integrating HTML content into a Sweet Alert popup using this code snippet Link: https://www.npmjs.com/package/vue-swal this.$swal({ title: '<i>Custom HTML</i>', html:`This is an <em> em ...

Is it possible to create a cylinder in three.js that emits light, giving it the appearance of a tube light?

As a beginner in Blender and three.js, I am eager to find resources that can help me master the art of creating scenes in Blender and then exporting them to three.js. I've noticed that in Blender it's possible to make any mesh emit light - how ca ...

JavaScript for Altering Viewport/Screen Width

Lately, I've been experimenting with creating a responsive button for our new website. The goal is to adjust the body width to 460px, simulating how our site would appear on mobile devices. While researching, I came across a technique that utilizes if ...

Conceal items by clicking using raycasting technology

I'm trying to hide scene objects by clicking on them, but after following multiple tutorials on "raycaster", I'm having trouble identifying where the issue lies. When I open my HTML file, all the objects are hidden, even though I've removed ...

Optimizing HTML and Script loading sequences for efficient execution

I have a query regarding the loading order of scripts in web browsers. I am interested in knowing the most efficient way to redirect users to a mobile website on the client side. For example, if I place a mobile detection script within the <head> se ...

What is the best way to adjust the fill animation of an inline svg based on the movement of the mouse within the parent div?

Can the fill of an inline SVG path be animated to change as the mouse moves across the page? ...

Struggling to fully understand and implement jQuery's click() method, as well as navigate event.data

Currently, I am in the process of developing a small script that allows users to dynamically change the background image of a webpage for design comparison purposes. Although I have a basic version working, I am facing a minor issue that I am determined t ...

What is the best way to position my Jchartfx area graph below my gridview?

When my page loads, the graph appears like this. It consistently shows up in the top left corner even though it should be positioned underneath the grid view as intended. var chart1; function createGraph(mpy) { if (mpy == undefined) mpy = 12.00; ch ...

When selecting an old list, only the most recently created ID is displayed, rather than the ID of the specific list being

I've set up a dashboard where I can create lists and have them displayed on the screen, but there seems to be an issue when trying to open any list as only the last created one opens. Can anyone point out what mistake I might be making? The technologi ...

Exploring the Depths of Scope Hierarchy in AngularJS

Upon inspecting the _proto__ property of an object I created, it is evident that it has been inherited from Object. https://i.stack.imgur.com/hcEhs.png Further exploration reveals that when a new object is created and inherits the obj object, the inherit ...