What steps can be taken to modify the default color on an MTL file?

See my Three.js Code Pen project:

https://codepen.io/FarhaNaseem/pen/NWdgYQJ

I have created a 3D model with a basic color setup in the MTL file. Is there a way to implement a color scheme where users can change colors by clicking? It should be possible to change colors for both the bottle and the cap separately.

For instance, the cap could have colors like Gold, Green, Blue while the bottle could offer options such as Yellow, Orange, Pink.

Additionally, is it feasible to achieve this without using the GUI.dat library?

Answer №1

When using the callback function for the MTLLoader.load method, you will receive a MTLLoader.MaterialCreator object, although it is not officially documented. This object is referenced as the material parameter in your code snippet:

var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( mtlURL, function( material ){ // <-- the MaterialCreator
  // ...
});

Once you have called the preload method, the materials property within the material object will be populated with the material names defined in the MTL file. Upon debugging, you will observe two instances of MeshPhongMaterial named blinn5SG and blinn8SG.

Adjusting color during loading

Prior to loading your object, you have the opportunity to manipulate the colors.

material.materials.blinn5SG.color.setHex( bottleColorHex );
material.materials.blinn8SG.color.setHex( capColorHex  );

Modifying color during runtime

To access the materials for color changes later on, you can store them in globally-accessible variables:

var mtlLoader = new THREE.MTLLoader();
var bottleMaterial = null;
var capMaterial = null;
mtlLoader.load( mtlURL, function( material ){ // <-- the MaterialCreator
  material.preload();
  bottleMaterial = material.materials.blinn5SG;
  capMaterial = material.materials.blinn8SG;
  //...
});

// later...

function changeColor( material, newHexColor ){
  material.color.setHex( newHexColor );
  material.needsUpdate = true;
}
// examples:
changeColor( bottleMaterial, newBottleHexColor );
changeColor( capMaterial, newCapHexColor );

During runtime, ensure to set material.needsUpdate to true, indicating to the renderer that the material has been altered.

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

Tips for incorporating JavaScript into .ascx pages

What are some ways to incorporate javascript in .ascx files? ...

Tips for achieving a standard dropdown appearance in a collapsed navbar with Bootstrap split button dropdown

Trying to create a navbar with a split dropdown button has been a challenge. The design either goes awry when the screen is narrow and the navbar is hidden behind the toggle, or it doesn't look right on a wider screen when the navbar is expanded. Cur ...

unable to successfully npm install canvas

For my GitHub repository, please visit here This project was actively developed until November of last year, after which I did not commit any changes. Today, I attempted to run the project again but encountered the following error. My current system versi ...

JavaScript's efficient way to target multiple class names

My goal is to extract and process JSON data into specific instances of a class named "slide_content" I want to achieve something like this: slide_content[0] Unfortunately, JS does not offer a method like getElementByClass(). The relevant API data can b ...

Generating dynamic dropdown menus using data from a database with the help of PHP and Ajax technologies

I'm currently working on creating a dynamic dropdown menu that will be populated with data retrieved from a database. I've hit a roadblock in parsing the data from a multidimensional array sent by a PHP file. Here's a snippet of my code: Se ...

Dragging and dropping elements on the HTML Canvas with the added feature of snap functionality

I have implemented a drag-and-drop circle feature inside an HTML canvas with the following code: var c = document.getElementById('myCanvas'); var ctx = c.getContext('2d'); width = c.width = window.innerWidth * 0.9; height = c.height ...

Import an array of dynamic modules with Webpack that are known during compilation

For my project, I have the requirement to import specific modules whose actual paths are only known during compile time. Imagine having components/A.js, components/B.js, and components/C.js. In my App.js, I need to include a subset of these modules that w ...

Is it possible to conditionally call the Apollo Client in my Vue template script?

I have a scenario where I pass a query to the apollo client in my template file using a script tag. However, I want to find a more efficient way to handle this without having to specify the query every time. My idea is to pass a boolean value through a pro ...

"Viewed By" aspect of Facebook communities

I'm working on implementing a feature that shows when a post has been seen, similar to Facebook groups, using JS and PHP. I've been able to track the number of times a post has been seen through scrolling actions, but now I want to determine if u ...

Determining the top element displayed in a div: A guide

Looking for an answer on how to determine the top visible element while scrolling? You may find some insights in this post: (Check if element is visible after scrolling). My scenario is slightly different - I have a scrollable div containing multiple ele ...

Error: Property 'config' cannot be accessed because it is null

Upon transferring my Angular project from my local computer to a Linux server, I attempted to launch the project using ng serve but encountered an issue where it opened a new file in the console editor instead. After some investigation, I tried running np ...

What is the JavaScript method for updating an HTML5 datalist to show new options?

When populating options dynamically into an HTML5 datalist, I'm facing an issue where the browser tries to display the datalist before all the options have loaded. As a result, the list either does not show up completely or only partially shows up. Is ...

"Using the map function in Javascript to iterate through an array and then implementing

I am working on a script that involves an array of the alphabet along with two sets of values. The goal is to determine if a given value falls within the range specified by these two values and then print out the corresponding letter from the alphabet. H ...

Using the Coinbase.com API with HMAC authentication in a Node.js environment

I recently delved into some node.js documentation, specifically crypto and https, in an attempt to utilize the coinbase.com API within my coin.js file to retrieve the bitcoin balance of my account. However, I am encountering errors. Upon running the code w ...

What's causing the member to be undefined?

client.on('raw', (e) => { if (e.t === 'MESSAGE_REACTION_ADD' && e.d.message_id === '813150433651851265' && e.d.emoji.name === "✅" ) { const guild = client.guilds.cache.get(e.d.gui ...

Can the ajaxsetup error handler be used with the POST method?

I have a strange question - does the global error handler applied when using ajaxsetup get triggered in case of an Ajax error on a POST request? I've tried handling Ajax errors in several places, but the error handler is only being hit for GET reques ...

What is the best way to retrieve data from ng-controller to use in the 'src' attribute of an <img> tag?

Check out this snippet of HTML: <div data-ng-controller="sampleCtrl" > <ul data-ng-repeat="item in sampleData"> <li class="message"> <img src="img-source" width="30" height="30"> <div class="message-text"> ...

Preventing the display of any object items that include a period character in AngularJS

There seems to be an issue with a JSON item not displaying correctly in AngularJS. error = { "name": [ "The name field is required." ], "salary.salary_id": [ "The salary.salary id field is required." ] } When attempting to ...

unable to clear form fields after ajax submission issue persisting

After submitting via ajax, I am having trouble clearing form fields. Any help in checking my code and providing suggestions would be greatly appreciated. Here is the code snippet: jQuery(document).on('click', '.um-message-send:not(.disabled ...

Assign the values from the axios response to variables within the exported const

Currently, I am incorporating axios into my vue.js application to perform an HTTP POST request and retrieve some variables for a vue-echart. However, I have encountered a bit of a roadblock in determining the most effective approach. The snippet below is ...