Uploading multiple textures for .obj files in ThreeJS

I've been attempting to upload a .obj file along with multiple .png and .jpg files that serve as its textures. However, I'm struggling to figure out how to properly handle these textures upon upload.

Here is the code I have so far:

var loader = new THREE.OBJLoader(manager);
loader.load(obj_path, function (obj) {

  model = obj;
  modelWithTextures = true;


  model.traverse( function ( child ) {

    if ( child.isMesh ) child.material.map = texture;

  } );

  var textureLoader = new THREE.TextureLoader( manager );
  var i;
  for (var i = 0; i < files.length; i++) {
    file = files[i];
    console.log('Texture Files:' + files[i].name);
    var texture = textureLoader.load(files[i].name);
  }
  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  setCamera(model);
  setSmooth(model);

  model.position.set(0, 0, 0);

  setBoundBox(model);
  setPolarGrid(model);
  setGrid(model);
  setAxis(model);

  scaleUp(model);
  scaleDown(model);

  fixRotation(model);
  resetRotation(model);

  selectedObject = model;
  outlinePass.selectedObjects = [selectedObject];
  outlinePass.enabled = false;

  renderer.render( scene, camera );
  scene.add(model);
});

Although I am utilizing the textureLoader, I am unsure of the next steps to take.

I am relatively new to threeJS and 3D models.

Any guidance or recommendations would be greatly appreciated.

Thank you.

Answer №1

If your code doesn't display much, it might be because you are rendering the scene before adding the model to it. Make sure to render the scene after making any changes, unless you have a render loop using requestAnimationFrame. Loading textures is also asynchronous, so use the callback of the .load method to respond better when loading is complete, for example, triggering render().

To load the textures within the model.traverse() callback, determine which texture corresponds to each mesh based on your data structure.

var files = ['mesh1_tex.jpg', 'mesh2_tex.jpg'];

var loader = new THREE.OBJLoader( manager );
var textureLoader = new THREE.TextureLoader( manager );

var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 0, 0, -100); // depending on model size and location

var renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );

var scene = new THREE.Scene();

loader.load(obj_path, function ( model ) {

  model.traverse( function ( child ) {

    if ( child instanceof THREE.Mesh ) {
    
      const file = files.find( f => f === child.name + '_tex.jpg');
      if (!file) {
        console.warn(`Couldn't find texture file.`);
        return;
      }
      
      textureLoader.load(file, ( texture ) => {
      
        child.material.map = texture;
        child.material.needsupdate = true;
        
        render(); // only if there is no render loop
      
      });
    
    }

  } );
  
  scene.add( model );
  
  camera.lookAt( model ); // depending on model location
  
  render(); // only if there is no render loop
  
});

function render() {

  renderer.render( scene, camera );
  
}

Note: This code is provided without testing.

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

Performing a Javascript ajax post of a canvas snapshot in "image/jpeg" format to an asp.net web form

Here is the JavaScript AJAX code snippet: var dataURL = canvas.toDataURL("image/jpeg"); var xhr = new XMLHttpRequest(); xhr.open("POST", "myPage.aspx", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechan ...

Utilizing Jquery and JavaScript to filter out specific HTML objects retrieved from an AJAX response

I'm encountering a puzzling issue with this snippet of HTML: <div id="1"> <div class="text"> Text for div 2 </div> <img src="images/image1.jpg"></img> </div> <div id="2"> <div class="text"> ...

Dragging an image in KineticJS gets stuck after the drag operation is completed

My experience with KineticJS has been positive so far, but I have encountered an issue with dragging images. In the example below, I have set the image to be draggable, but after the initial drag, it seems like the image can't be moved again. var sta ...

Developing dynamic checkbox components using jQuery - unusual behavior in Internet Explorer

I am dynamically creating checkbox elements using jQuery and appending them to a specified node as shown below var topics = ['All','Cat1','Cat2']; var topicContainer = $('ul#someElementId'); $.each( topics, functio ...

I must align a bootstrap modal(dialog) based on the opener's position

Using a bootstrap modal for the settings dialog in an angularJS app, but facing an issue where it opens in the center of the page by default instead of relative to the opener. Looking for a solution to keep it positioned correctly when scrolling. Code: M ...

The screen reader seems to be malfunctioning as soon as I include this particular code

//Finding the height of the header let headerHeight = document.querySelector('header'); let height = headerHeight.offsetHeight; //Adjusting the #navbarNav's top margin to accommodate the header let nn = docu ...

Navbar Collapse in Bootstrap 5 not functioning properly when losing focus

I am working on a project as a beginner where I am coding a site navbar using Bootstrap 5. The issue I am facing is that currently, the navbar does not collapse when I click away after expanding it. My goal is to make it so that the navbar automatically co ...

What strategies can be used to effectively manage multiple asynchronous requests?

I have two requirements: one is to load an image (which will take a long time on the backend server), and the other is to perform an AJAX request. I would like it to be structured like this: $.when( [perform image loading] [perform ajax request] ).t ...

Sending data to a PHP page to maintain state in an Angular application

Here is my current setup: In a dynamic Angular environment, I have various states connected to PHP pages. These PHP pages rely on specific data variables, typically provided as GET parameters outside of Angular. Now, I am looking for a way to switch to a ...

Tips for eliminating the trailing slash from the end of a website article's URL

I've recently delved into learning Gatsby, and I've encountered an issue with the Open Graph tag in my project. The og:image is displaying a different image than the intended thumbnail for the article. Here's an example article - . When try ...

Employing multer in conjunction with superagent to enable file uploads from a React application

I am new to using multer and experiencing some difficulties with it. My goal is to upload an image file from a react client using the superagent library to my server. However, the req.file data always shows as undefined in my code: On the server side : ...

Tips for updating an ASP.NET MVC page when the browser back button is pressed

Have you ever encountered the issue where clicking the browser back button on any ASP .NET MVC page does nothing, and the page does not update unless you hit F5 to refresh it? It seems that the main problem lies in making changes to the DOM of the page, s ...

Modify the design of the button in the CSS code

I am facing an issue with the layout of the Visible Columns button and unable to standardize it like the buttons above using CSS enter image description here The code snippet for the Visible Columns button is as follows: import React, { useState, useEffe ...

Angular can be used to compare two arrays and display the matching values in a table

Having two arrays of objects, I attempted to compare them and display the matching values in a table. While looping through both arrays and comparing them by Id, I was able to find three matches. However, when trying to display these values in a table, onl ...

Developing entities in Express.js

My express app is currently fetching data from an external API through the following endpoints: api.com/companies (GET, POST) api.com/companies/id (GET, PUT) To improve maintainability and avoid code repetition, I am looking to create a model for handlin ...

The Lightbox containing an IFrame is experiencing flickering issues when links are clicked

I am experiencing a similar issue with this post: How can I resolve flickering in IFrames? Unfortunately, I have yet to find a solution (and I'm worried about receiving negative ratings too :) ). Due to the fact that my website is on an intranet, I ...

How can we ensure that a child directive in AngularJS shares the same data as its parent?

My child directive needs access to the same data as its parent pages. What would be the most effective method for sharing this data? Should the child directive fetch the data separately, or should the parent send it through attributes? ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

Navigate to the adjacent IDs

I have multiple sections with varying content and links (previous and next) to navigate to the next section. Initially, everything functions properly. However, when adding a new section in between existing ones, I am required to update all the ids to ensu ...

Receiving a blank array from the firestore database

I have written a code for the LeftBar Component where I am trying to retrieve data stored in the "contacts" document in Firebase. However, I am getting an empty array and I'm not sure why this is happening. Additionally, I would like to know how to ac ...