Guide to using three.js for applying a texture to an mtl and obj file

I'm attempting to apply a png file onto an mtl/obj file.

Prior to mapping

However, after mapping, the mtl texture seems to disappear.

After mapping

What should I do? My English skills are not great. If you have trouble understanding my question, please leave a comment.

This is my code:

           var onProgress = function(xhr) {
           var percentComplete = xhr.loaded / xhr.total * 100;
           console.log(Math.round(percentComplete, 2) + '% downloaded');
        };


        var onError = function(xhr) {};

        THREE.Loader.Handlers.add(/\.dds$/i, new THREE.DDSLoader());

        var loader = new THREE.ImageLoader();
        loader.load("../img/ang.png", function(image) {

           texture.minFilter = THREE.LinearFilter;   
           texture.image = image;
           texture.wrapS = THREE.ClampToEdgeWrapping;
           texture.wrapT = THREE.ClampToEdgeWrapping;
           texture.offset.set(-3, -9.5);
           texture.repeat.set(13, 13);
           texture.needsUpdate = true;

        },onProgress,onError);

        var mtlLoader = new THREE.MTLLoader();
        mtlLoader.setPath('../models/');
        mtlLoader.load('nag-green.mtl', function(materials) {

           materials.preload();

           var objLoader = new THREE.OBJLoader();
           objLoader.setMaterials(materials);
           objLoader.setPath('../models/');
           objLoader.load('nag-green.obj', function(object) {

              object.traverse(function(child) {

                 if (child instanceof THREE.Mesh) {
                    child.material.map = texture;
                 }
              });

              object.name = "object";
              object.position.y = 0;
              scene.add(object);

           }, onProgress, onError);
        });

My goal is to map the 'ang.png' file over the t-shirt in this manner

desired outcome

Thank you for your suggestion Radio, I tried that approach but it doesn't achieve what I intend to do.

assigning a name to material and mapping

Answer №1

All child meshes have been assigned the 'ang.png' texture, but it might be more efficient to apply the texture selectively based on certain conditions within the traverse function. Consider implementing a conditional statement to ensure the texture is only applied where necessary.

When the material was initially loaded into the mtl file, it should have been assigned a specific name such as "torso". It's important to identify and target this specific material when applying textures. For instance, you can query the material name within the traversal process as shown below:

          object.traverse(function(child) {
             if (child instanceof THREE.Mesh) {         
                 if(child.material != undefined){
                    if(child.material.name=="torso"){
                      child.material.map = texture;
                    }
                 }
             }
          });

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 state remains unaltered within the confines of the useState hook and useEffect function

I encountered a similar issue to the one discussed in this particular question The code provided was extensive, so I created a simplified version of the problem. (I apologize if there was an error in my approach) Essentially, I have a main component and ...

The 'ReactType' type is not generic within material-ui@next

After installing material ui@next, I encountered an error in the node modules. ERROR in [at-loader] ./node_modules/material-ui/Avatar/Avatar.d.ts:8:15 11:31:52 web.1 | TS2315: Type 'ReactType' is not generic. 11:31:52 web.1 | ERROR in ...

Tips for handling data strings using axios

In my node.js project, I am following a manual and attempting to display data obtained from jsonplaceholder app.get('/posts', async (req, res) => { const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); ...

JavaScript ECMAScript 6 - WARNING: "Decorators can only be applied to a class when exporting"

In ECMAScript 6, I am attempting to export a function so that I can import it and utilize it in other files for the sake of writing DRY code. However, an error message is appearing: You can only use decorators on an export when exporting a class (16:0) ...

What methods can be used to prevent external URLs from being crawled by using hashing?

Recently, I came across a post on a coding forum discussing how to hide links from Google using JavaScript. The idea is to mask the URLs from being crawled by Google while still making them accessible to users. In my case, I have external URLs that I want ...

Communicating PHP variables with JavaScript through AJAX in a chat application

Hello there! I am currently in the process of developing a chat application for my website that includes user registration and login. My backend server is built using NodeJS to leverage SocketIO capabilities. Within my index.php file, I have implemented ...

Failed installation of Semantic-ui through npm encountered

Encountering an error while attempting to install semantic-ui through npm for a new project. Here are the version details: $ node -v v16.14.0 $ npm -v 8.10.0 $ npm i semantic-ui npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Breaking down a div with jQuery - tips and tricks!

I have a question regarding jQuery. Consider the following structure: <div class="page"> <p>Lorem ipsum....</p> <p>Lorem ipsum....</p> ... </div> I want to transform it into this format: <div class="pa ...

Ways to transmit information among Vue components

I am trying to figure out how to pass data from the Module variable in CoreMods.vue to ExternalWebpage.vue using Vuex. I want the CoreModule state to be watched for changes in the external webpage. This is my store.js setup: import Vue from 'vue ...

Connect directly to the DOM without using an event

A jQuery function is included in my code: $('#big-bad-bold-button') .on('click', aloha.ui.command(aloha.ui.commands.bold)); This function binds the click event. Is there a way to achieve the same binding without requiring a click? ...

Removing zeros from a one-dimensional tensor in TensorFlow.js: A step-by-step guide

If I have a 1D tensor (distinct from an array) with the values [0,2,0,1,-3], my goal is to retrieve only the non-zero values. Using the example provided, I want to receive [2,1,-3] as the output. Is there a way to achieve this in TensorFlow.js? ...

Typescript: Add a new variable preceding a specified string

fetchArticle(articleId: string): Observable<any> { return this._http.get(`${this._url}/${articleId}`) .map((response: Response) => response.json()) .do(value => console.log(value)) .catch((error) => Observable.throw(err ...

Are the frameworks Vue, Angular, and React known for

During a conversation, I came across an interesting viewpoint criticizing popular frameworks such as Angular, Vue, and React. It was argued that these frameworks have a significant disadvantage: apart from the API part that interacts with the server's ...

how to retrieve a value from a lookup field in CRM 2015 with JavaScript

How can I retrieve the email of a contact when I already have their ID? function getEmailFromContactID(){ var contactId, contactName, contactEmail, contactObject; // mbmhr_employee is the lookup field name that we want to retrieve values from c ...

transferring data through hyperlink tags

In PHP, I am currently developing a module that enables me to view and access all the users on my website. To achieve this, I am retrieving all the user names from the database and creating anchor links for them simultaneously. Now, I want to associate dat ...

When attempting to import the OrbitControls.js file, Three.js encounters an error and fails

I am completely new to javascript and unfamiliar with working with libraries. I am currently experimenting with basic three.js code, but unfortunately facing issues that I cannot seem to resolve. Following the documentation on Threejs.org, I have set up a ...

Create movement for an object when it is clicked and when the mouse cursor enters or leaves the object, as well as other

I am struggling with the layout of my webpage, which consists of 3 main div elements. https://jsfiddle.net/wpztofb7/ <body> <div id="topBox" class="otherBox"> TEST TOP </div> <div id="middleBox" class="middleBox"> ...

JSON object containing multiple elements in JavaScript

I have a JavaScript JSON object const student = { name: "bob", age: 7, grade: 6 } and I can send it to my Web API using the axios POST command with JSON.stringify(student) To build multiple student objects from an array by looping through and p ...

Display a fresh state using React Router

I'm currently facing an issue with trying to update the title value in the state based on the router input. Despite having proper code compilation, the title remains an empty string. Can someone help me figure out why this is happening? class Header ...

The focus of the input is lost when the value is being edited, specifically in the case where ngFor and ng

I'm facing an issue with a simple list that binds two-way to a parameter hero in my hero.component.ts. Whenever I begin typing in the input field, it seems to lose focus and I have to click on it again. How can I ensure that users are able to edit th ...