Enhance your THREE.js projects with dynamic textures using Promises

Can anyone offer guidance on how to utilize promises for loading textures in THREE.JS? I've looked into their functionality, but could really use a practical example. Specifically, I am attempting to load an image (img.png) onto a cube mesh.

I prefer not to rely on JSON for this task.

Answer №1

I created a custom function called loadTexture that utilizes THREE.TextureLoader and wraps it in a Promise for asynchronous loading.

// Custom function to load texture with Promise
function loadTexture(url) {
  return new Promise(resolve => {
    new THREE.TextureLoader().load(url, resolve)
  })
}

// Example of how to use the custom function
loadTexture('myCustomTexture.jpg').then(texture => {
  var geometry = new THREE.SphereBufferGeometry(500, 60, 40)
  var material = new THREE.MeshBasicMaterial({ map: texture })
  sphere = new THREE.Mesh(geometry, material)
  scene.add(sphere)
})

Answer №2

Check out this snippet of code showcasing THREE.ImageUtils.loadTexture in action using THREE.js:

THREE.ImageUtils = {

  crossOrigin: undefined,

  loadTexture: function ( src, map, handleLoad, handleFail ) {

    var loader = new THREE.ImageLoader();
    loader.crossOrigin = this.crossOrigin;

     var textureImage = new THREE.Texture( undefined, map );

     loader.load( src, function ( img ) {

        textureImage.image = img;
        textureImage.needsUpdate = true;

        if ( handleLoad ) handleLoad( textureImage );

      }, undefined, function ( err ) {

       if ( handleFail ) handleFail( err );

     });

    textureImage.sourceFile = src;

    return textureImage;

   },
 

You can easily encapsulate this functionality within a custom function that utilizes Promises (in ES6 syntax):

loadTextureAsync (src, map) {

 return new Promise ((resolve, reject) => {

          const onLoad = (texture) => resolve (texture)

         const onError = (err) => reject (err)

         THREE.ImageUtils.loadTexture(
           src, map, onLoad, onError)
  })
}

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

Avoid clicking on the HTML element based on the variable's current value

Within my component, I have a clickable div that triggers a function called todo when the div is clicked: <div @click="todo()"></div> In addition, there is a global variable in this component named price. I am looking to make the af ...

Unlocking nested JSON data in React applications

Encountering an issue while retrieving a nested JSON object from a local API endpoint /user/{id}. Here is an example of the JSON object: {"userId":122,"name":"kissa","email":"<a href="/cdn-cgi/l/email-protect ...

Utilize the function with another function (difficult to articulate)

Apologies in advance for my beginner question. Review the code snippet below: var dt = new Date(t*1000); var m = "0" + dt.getMinutes(); Depending on the t variable (unix time), the output can be one of the following: m = 054 // 54 minutes m = 03 // 3 min ...

Which approach yields better performance: setting all dom events simultaneously, or incrementally?

Is it more effective to attach event listeners permanently or only when needed? For example, consider a scenario where you have a dropdown menu in your HTML that opens when clicked. Within this menu, there is a close button that closes the menu upon click ...

Altering the hues of several logos every second

I am looking to create logos that change color every second with a smooth transition: i{ color: blue; transition: color .5s; } I want the logos in the i class to smoothly transition from white to red in a loop. This is part of the code for my websit ...

Having trouble retrieving the JSON value as it returns undefined

Having trouble extracting specific values from JSON data. I'm trying to retrieve the value of result.datafeed[0].prod[0].vertical[0].deviceProductJson[0].product_brand, but it keeps returning as undefined. To investigate further, I examined the stru ...

Is it possible to select options in AngularJS based on certain criteria?

I created an AngularJS select menu that is currently functioning correctly: <select name="s1" id="s1" multiple="multiple" data-native-menu="false" data-role="none" ng-model="userlistSelect" ng-options="u.userId as u.fi ...

Is it possible to adjust shadows in Three.js without modifying the mesh itself?

My current project involves creating an app that allows users to manipulate 3D objects in a scene while observing the effect of their changes on the ground shadow: https://i.sstatic.net/WTks9.png In this particular scene, there is a yellow cylinder casti ...

Tips for displaying Facebook comments with JavaScript

Can anyone help me figure out how to customize the data-href for Facebook comments using JavaScript (jQuery)? I tried incorporating the code below, but it's not displaying anything in the div col2. $("#col2").html( id+"<div class='fb-comm ...

Sharing asynchronous data between AngularJS controllers

Among the multitude of discussions on sharing data between controllers, I have yet to come across a satisfactory solution for my particular scenario. In my setup, one controller fetches data asynchronously using promises. This controller then creates a co ...

Fixing extended properties on an express request can be done by following these steps

I've been working on a JavaScript middleware where I can extract user information using the "req" object in the route handler. When I log currentUser, I get the expected value, but I'm encountering a TypeScript error warning: Property 'curre ...

What is the method used by react-create-app/react-scripts to locate the entry point file?

I'm confused about how npm start locates the src/index/js file to begin the rendering process in this helpful tutorial. I've searched everywhere but can't seem to find any information on the configuration. Can anyone provide some insight? ...

I encountered an unexpected obstacle while reloading my Next.js application with animejs. The error message reads: "SyntaxError: Unexpected token 'export'." This unwelcome occurrence took place during the

Encountering an error with animejs when reloading my Next.js app: An unexpected token 'export' is causing a SyntaxError. This issue occurred during the page generation process. The error originates from file:///Users/.../node_modules/animejs/lib ...

Can you explain the distinction between these codes?

function Example() { this.display1 = function() { alert(1) } } Example.prototype.display2 = function() { alert(2) } var e = new Example e.display1() e.display2() display1 and display2 both have the ability to trigger an alert showing a number. Do yo ...

Sending an AJAX request to a Controller Action using an Object as input

I am currently using an AJAX call to a Controller within an ASP.NET MVC solution. The code snippet for the AJAX call is as follows: $.ajax({ url: "ControllerClass/ControllerMethod?date=" + date, type: "POST", dataType: 'json&a ...

The error "Call to a member function exports() on array" occurs when attempting to use the

As I attempt to send an array of values to the jobExport() collection, I encounter an error stating Call to a member function jobsExport() on array. I comprehend the necessity for the collection to be populated with modal collection value. However, my goal ...

"Encountered a problem while setting up the Mailgun webhook to handle both multipart and URL encoded

I have been working on creating a web hook listener for Mailgun, and I encountered an issue when I realized that Mailgun can post webhooks using either multipart or x-www-form-urlencoded content-types. Currently, my code uses Multer to handle multipart b ...

What is a more dynamic way to assign attributes to elements without directly embedding them in the HTML code?

For my unique scenario, my goal is to assign the attribute target = "_blank" to all <a> elements within a specific div in order to open them in new tabs. This concept could potentially be applied to any element and any attribute. I am curious if the ...

Seeking assistance in loading the webpage content when the button is clicked

<html> <body> <a href="samepage.php"><img src="button.png"></a> <div> //page content, database queries, calculations etc </div> </body> </html> I'm interested in loading the DIV content dynamicall ...

Issue with executing Jquery in PUG file: The $ sign is not being recognized despite jQuery being imported

I am encountering an issue where my jQuery code placed inside a pug template is not executing as expected. Despite including the jQuery file, when trying to run a jQuery function, I receive the error below: 40| P 41| ...