Updating material for a three.js .obj file with the click of a button

Struggling to figure out how to use a button to change the .mtl file associated with my .obj in three.js. Any suggestions on accomplishing this would be greatly appreciated!

Below is the code I've been working with, based on the objmtl loader example from threejs.org. So far, I have only managed to toggle the visibility of the obj using a button. However, I am eager to implement additional buttons that can swap out the .mtl files to showcase different colors and properties.

var mtlLoader = new THREE.MTLLoader();
                mtlLoader.setBaseUrl( 'examples/obj/male02/' );
                mtlLoader.setPath( 'examples/obj/male02/' );
                mtlLoader.load( 'male02_dds.mtl', function( materials ) {

                    materials.preload();

                    var objLoader = new THREE.OBJLoader();
                    objLoader.setMaterials( materials );
                    objLoader.setPath( 'examples/obj/male02/' );
                    objLoader.load( 'male02.obj', function ( object ) {


                        object.position.y = - 95;
                        dude = object;
                        scene.add( dude );

    info.innerHTML += '<br/><br/><input id=pants2 type="button" onclick="dude.visible = false" value="Dude: OFF"/>';
    info.innerHTML += '<input id=pants2 type="button" onclick="dude.visible = true" value="Dude: ON"/>';

Answer №1

If you're able to work without the .mtl file, here is an alternative solution:

texture = new THREE.TextureLoader().load('path/to/texture.jpg');
sectexture =  new THREE.TextureLoader().load('path/to/second_texture.jpg');
lambert = new THREE.MeshLambertMaterial({color: 0xffffff, map: texture});
objLoader = new THREE.OBJLoader();
objLoader.setPath( 'examples/obj/male02/' );
objLoader.load( 'male02.obj', function ( object ) {
    object.traverse(function(child) {
        if (child instanceof THREE.Mesh){
            child.material = lambert;
        }
    });
    scene.add( object );
}, onProgress, onError );

By using this method, you can easily load your texture into the lambert material and switch between textures using lambert.map=texture or lambert.map=sectexture.

[EDIT] The error with child.material has been corrected.

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

Copying Objects in JavaScript Using Deep Cloning

My current project involves using Nodejs to create a deep copy of an object generated by Squel, a query building library. The main dilemma lies in how to replicate the exact filteredQuery variable. The object is initialized with: filteredQuery = squel.sel ...

Ensure to correctly add to an array while managing button clicks

As I work within my function, my goal is to slowly accumulate an array of responses from user interaction before passing it off to an API. However, I've noticed that different methods of appending to the array result in overwriting the existing data w ...

Loading HTML content in a WPF WebBrowser without encountering security messages

Currently, I am developing a WPF application in which I create the content of an HTML file as a string (including some JavaScript functions for calculations). After generating the string, I save it as an HTML file on my local disk and then reload it using ...

What methods could I use to prevent the WYSIWYG buttons from automatically linking?

I've been working on creating an editor but I'm facing a small issue. Every time I click on a button (such as bold or italic), it follows a link instead of performing the desired action. Here's a snippet of what I've tried so far: fu ...

Error with the mongo (1.4.4) query

After running the query like this : collection.find({ "position": { $in: [ 1, 2 ] } }).toArray().... The correct result is returned. However, when I try using $and or $or, such as: collection.find({ $or: [ { "position": 1 }, { "position": 2 } ] }).toAr ...

How to Handle Overlapping Divs in HTML?

I have a sizable container div with various dynamic divs nested inside. These child divs are often padded to the left and contained within another div that is also padded on the left. My goal is to make the overall container div (which has a border) adju ...

Ezpay: The CSRF token is not permitted in the header of the Laravel application

After adding the <script> $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } }); </script> to the layout blade, every step in the checkout process requires a CSRF token for the POST request. However, during the to ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

Executing numerous xhttp.send requests within a single webpage

Hey there, I'm facing an issue with xhttp.send(); as it keeps giving me the error message net::ERR_EMPTY_RESPONSE Here is a snippet of my code. Whenever a user clicks too quickly, they get kicked off the page. Is there a way to prevent this? docum ...

Using the MoveToElement and click functions in Protractor with Node.js for automated browser

Trying to click on a checkbox in our application. I have successfully implemented it in Selenium Java using the code below, but struggling to do the same in Protractor Node.js. Any assistance would be appreciated. Selenium- Java : Actions actions ...

Is it possible to determine the height of a div after it has been rendered using the .resize method?

In my current structure, <div id="A"> <div id="A1"> <div id="B1"></div> <div id="B2"></div> </div> <div id="A2"></div> </div> A2 and B2 contain tables, while B1 has 4 checkboxes. I&a ...

The initialization of public variables in the ngOnInit function is currently set

I am encountering an issue with public variables in my Component that are linked to ThreeJs. When I try to utilize them within the ngOnInt method, I am running into an error. Variables export class CustomizerComponent implements OnInit { public threeJsV ...

Fade in images using jQuery

I am having issues with fading in and out images using jQuery, it doesn't seem to be working as expected. I think there might be something crucial that I am missing. Take a look at the script below: var count = 1; setInterval(function() { ...

"Utilizing jQuery Autocomplete with an external data source and interactive row additions

I have come up with a plan: When the user types in the search textbox, it will show autocomplete suggestions and display the result on textbox 1, textbox 2, textbox 3. The user can then enter the desired Quantity in textbox 4. After finding an item and ...

Transition smoothly between two images with CSS or jQuery

I am working on a project where I need to implement a hover effect that fades in a second image above the initial image. The challenge is to ensure that the second image remains hidden initially and smoothly fades in without causing the initial image to fa ...

Accessing a confidential document from a secure S3 bucket using React.js - A guide

Looking to access a public file on S3 in React.js? Here's how: fetch('https://bucketnmame.s3.amazonaws.com/folder1/folder2/file.txt') .then ((response) => response.text()) .then (data => { console.log(data) }); Now, what if you need ...

I can't seem to get my code to work more than once

My code seems to be working only once. This is the HTML code snippet I am using: <span id="0" class="add-title">add title</span> And here is my JavaScript code: jQuery(document).ready(function($) { var iTitlesArray = []; $(document ...

Delaying Jquery on scroll Event

Hey there, I've got a set of icons that I'd like to reveal one by one as you scroll down. I've incorporated some animations from , but now I'm wondering how I can implement a delay function in my jQuery so the icons appear sequentially ...

What is the best way to break out of the outermost if statement when it is nested within another if statement?

Currently, I am exploring the capabilities of the HTML5 speech recognition API to display spoken words on the screen. In my experiment, I have set up a trigger word that needs to be said first before other words can be detected, similar to how Apple's ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...