Adjust the color of a three.js mesh with the help of gui.dat

Loaded into my three.js mesh is an STL file:

    var loader = new THREE.STLLoader();         
    var materialmodel = new THREE.MeshPhongMaterial( 
        { 
            color: 0xFF0000, 
            specular: 0x222222, 
            shininess: 75 
        } 
        );

    function model()    
        {

            loader.load( 'models/stl/binary/model.stl', function ( geometry ) {
                var meshMaterial = materialmodel;
                var model = new THREE.Mesh( geometry, meshMaterial );
                model.scale.set( 0.02, 0.02, 0.02 );        
                model.castShadow = true;
                model.receiveShadow = true;
                model.geometry.center();                            
                scene.add(model);
                render();
            } );
        }
    model();

Upon calling the model function in my page, the rendering of the model happens as expected.

I aim to incorporate dat.gui as a simple interface for real-time changes.

My initial attempt involves altering the color of the model.

The code snippet utilised looks like this:

            var params = {
                modelcolor: 0xff0000,  
            };

            var gui = new dat.GUI();
            var folder = gui.addFolder( 'Model Colour' );
            folder.addColor( params, 'modelcolor' )
                .name('Model Color')
                .listen()
                .onChange( function() { materialmodel.MeshPhongMaterial.color.set( params.modelcolor); } );                  
            folder.open();

DAT.GUI's color picker functions correctly, allowing me to select a hex value which displays accordingly. However, the model/mesh fails to update with the chosen color.

I am contemplating whether the issue lies in how I am changing the color using

materialmodel.MeshPhongMaterial.color.set( params.modelcolor);
(despite trying various methods without success).

I recently came across a post here (in one of the answers) where the user employs

model.material.color.set(params.color)
in their example. My material properties are stored within a variable using THREE.MeshPhongMaterial..... How can I dynamically alter the color of a nested property contained within a variable like mine?

Answer №1

I'm not sure why you decided to use .listen(), perhaps there was a specific purpose behind it.

In the .onUpdate function, you referenced materialmodel as a material, but then tried to set the .MeshPhongMaterial property which does not exist. It seems like this might have been an oversight.

Check out this functional example below:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.setScalar(10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));

var materialmodel = new THREE.MeshPhongMaterial({
  color: 0xFF0000,
  specular: 0x222222,
  shininess: 75
});
var geometrymodel = new THREE.SphereBufferGeometry(5, 32, 16);

var model = new THREE.Mesh(geometrymodel, materialmodel);
scene.add(model);

var params = {
  modelcolor: "#ff0000"
};

var gui = new dat.GUI();
var folder = gui.addFolder('Model Colour');
folder.addColor(params, 'modelcolor')
  .name('Model Color')
  .onChange(function() {
    materialmodel.color.set(params.modelcolor);
  });
folder.open();

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/96/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.2/dat.gui.min.js"></script>

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

I am encountering an issue where Angular oidc-client Popups are failing to redirect properly within an iframe after successfully logging into

I recently integrated Azure AD with my Angular web application using oidc-client. When clicking on the login button, a popup opens with the URL https://login.microsoftonline.com. It prompts for Azure AD username and password, and upon successful login, a c ...

Instructions for setting a cookie to conceal a notification bar upon the second page load

I am looking for the following scenario: When a new visitor lands on my website, a notice bar fixed to the bottom of the screen becomes visible. After clicking on a menu item to navigate to another page, a cookie is set upon the second page load. This co ...

What could be hindering my jQuery function from running the Ajax script?

My jQuery function is supposed to retrieve two values, one for school/college and one for state, and send it to the controller class under the URL "Type&State". However, for some reason, the data is not being passed and nothing is shown in the console ...

Tips for validating multiple forms on a single page without altering the JavaScript validation structure

My JSP page currently consists of two forms: <body> <form id="1"></form> <form id="2"></form> </body> Only one form is visible at a time when the page is viewed. A JavaScript validation file is used to check the ...

What is the best way to access a specific value within a two-layered JSON object using JavaScript?

Here is an example of JSON data that I am working with: {"0":{"access_token":"ya29.MgCIagT8PCpkRSIAAAAl-XYEA37OjX_GBAv4so6qv0Gowc5XD3Bp6MuwYAPmnNuwgz7ElXsRwXqGWL4aZpA","token_type":"Bearer","expires_in":"3600","scope":"https://www.googleapis.com/auth/plus ...

Is there a way to refresh the page in NextJs whenever the parameters are modified without the need for reloading?

Currently, I am navigating on http://localhost:3000/?groupId=chicago&dayOfWeek=tuesday. Despite pressing a button on a component, the desired outcome of transitioning to another day, like Thursday, is not occurring. import { useRouter, usePathname, use ...

What is the process for establishing a key on the request header to authenticate in Node.js?

I am a novice in the world of nodejs. My current project involves creating a basic server that writes JSON data to a CSV file. However, I have encountered a stumbling block: For authentication purposes, the request header must include an “appKey” para ...

Prevent pinch zoom in webkit (or electron)

Is there a way to prevent pinch zoom in an electron app? I've tried different methods, such as using event.preventDefault() on touchmove/mousemove events in JavaScript, adding meta viewport tags in HTML, adjusting -webkit-text-size-adjust in CSS, and ...

Is concealing content using Javascript or jQuery worth exploring?

While I have been hiding content using display:none; in css, there are concerns that Google may not like this approach. However, due to the needs of jQuery animations, it has been necessary for me. Recently, I have come across a new method for hiding conte ...

arranging a collection of images based on their values in increasing order

cardShop is a container with various images, each with its own unique ID and value attribute. These values consist of two numbers separated by a comma, such as 2000,500 or 1500,200. My goal is to sort these images in ascending order based on the first numb ...

Is it possible for you to provide both a status code and an HTML webpage?

I've been working with the express framework in node, but I'm unsure if what I'm doing is best practice. I want to send a specific status code such as res.status(200).send("Success"); when the form input matches the server, and another statu ...

What are the steps for adding node packages to sublime text?

Is there a way to install node packages directly from Sublime Text instead of using the command line? If so, what is the process for doing this? I'm not referring to Package Control; I'm specifically interested in installing npm packages like th ...

The Vue.js transition feature seems to be malfunctioning when trying to display a modal

I can't figure out why my animation isn't working with Vue transitions. Here is the code I have: <template> <teleport to="body"> <div class="modal-overlay" v-if="loading"> <transitio ...

The project runs smoothly on my local host, but encounters an issue during the build process

I am currently working on a Preact-CLI project that utilizes Preact-Router. Everything functions as expected when testing on localhost, but once the project is built and deployed to production, issues arise. One particular page within the project pulls co ...

Tips for transferring a JSON object from an HTML document to a JavaScript file

Here is the code snippet: <script id="product-listing" type="x-handlebars-template"> {{#each productsInCart}} <tr> <td> <div class="imageDiv"> <img ...

Python Flask login screen not showing error message

Currently, I'm in the process of developing a login screen that incorporates Bootstrap and utilizes jQuery keyframes shaking effect. The backend functionality is managed by Flask. However, I seem to be encountering an issue where the error message "Wr ...

Gathering user information through Javascript to dynamically populate an HTML document

Looking to utilize JavaScript to extract the value entered in a search bar and then display it in HTML. function pullValue() { var search = document.getElementById("search-bar") } How can the extracted data be inserted into the following: <h3 class ...

I recently created a "dist" folder through Babel. Is it possible to integrate the files within this folder directly into a fresh React project?

I have a React library that is available on npm. My process for publishing it involves the following steps: To begin, I create a folder called dist using Babel by executing this command- babel ./src -d ./dist Next, I upload the resulting dist directory ...

Enable or disable multiple input options based on dropdown selection changes

I am currently working on a feature where multiple text boxes need to be enabled or disabled based on the selection made in a dropdown box. What I want to achieve is that regardless of which option is selected in the dropdown, all fields should be enable ...

Maintain user authentication status in Vuex after page refresh

Hello, I have implemented a setup using Vuex and Laravel sanctum for user authentication. Below is the code snippet from my Vuex file auth.js: import axios from 'axios' export default { namespaced: true, state:{ authenticated: ...