Unable to modify textures with a click on threejs

I am attempting to change the textures and colors of an object when clicking on separate cubes. I have encountered a challenge where I can only change the color of the object once, even when using a for-loop, and only if there are no previous textures or colors applied to the object. However, if the object already has a color, I am unable to change it. Do I need to include some 'needsUpdate' statement? I tried doing so but without success. Please review my onclick function.

EventsControls.attachEvent('onclick', function() {
    var colors = ['White', 'blue', 'gold'];
    for (var i = 0; i < colors.length; i++) {
        object.traverse(function(child) {
            if (child instanceof THREE.Mesh) {
                if (child.material.name == "Sofa_Leather") {
                    child.material = colors[i]; 
                    child.material.needsUpdate = true;
                    child.material.buffersNeedUpdate = true;
                    child.material.uvsNeedUpdate = true;
                    child.receiveShadow = true;
                }
            }
        })
    }
});

Please point out any errors in my approach. Thank you.

// Tried again with the below code, however, I was still only able to change one color. I suspect I may be using the 'needsUpdate' incorrectly.


var index = 0;    
var colors = [0xfffeef, 0xffff00, 0x000fff];

object.traverse( function(child) { 
    if (child instanceof THREE.Mesh) {

        if (child.material.name == "Sofa_Leather") {  
            if(index == colors.length) index = 0;
            child.material.color.setHex(colors[index++]);

            child.material.needsUpdate = true;
            child.receiveShadow = true;
        } 
    }
})

Answer №1

If you’re looking to achieve this effect, try the following code snippet:

material.color.setHex(0xffffff * Math.random()); // set color randomly

UPDATE:

Alternatively, you could also use this method:

var colors = [0xff0000, 0x00ff00, 0x0000ff]; // red, green and blue
if(index == colors.length) index = 0;
line.material.color.setHex(colors[index++]);

Take a look at this revised jsfiddle

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

Unable to retrieve the regex value with an alternate label

Here is a RegExp expression that I am currently using: const regex = new RegExp('<(.*)>' + text + '<(.*)>'); renderer.setProperty(node, 'innerHTML', node.innerHTML.replace(regex, '<$1>' + replaceTe ...

Algorithm that continuously increases a given date by 3 months until it surpasses or matches the specified creation date

I am currently working with QuickBase, a platform that involves HTML. My goal is to develop a code that can take a [fixed date] (always in the past) and increment it by 3 months until the MM/YYYY exceeds or equals the MM/YYYY of the [creation date]. Once t ...

Transform the JSON response from MongoDB into a formatted string

var db = mongoose.connection; const FoundWarning = db.collection('warning').find({UserID: Warned.user.id, guildID: message.guild.id}).toArray(function(err, results) { console.log(results); }) I have been attempting to ...

Is it possible to create a central hub for all routes in a large AngularJS application?

Developing a large angularjs application with the intention of utilizing require.js for lazy-loading additional modules. The main question at hand is whether to create a comprehensive route.js file containing all the routes to other modules, or if each mod ...

What is the best way to generate a static header in nextJS?

I am looking to create a static navbar without needing client-side fetching. Currently, I am using Apollo GraphQL and my _app.js file is set up like this: import React from 'react'; import Head from 'next/head'; import { ApolloProvider ...

AJAX-powered Form Validation

I am in the process of creating a login form that includes three input fields: one for entering a username, another for entering a password, and a submit button to log in. Currently, I am utilizing AJAX to validate the login information directly on the cl ...

Tips for making an AJAX request using jQuery

I have a new project that involves collecting user data and displaying it on the same page. I was able to successfully implement an Ajax call using JavaScript, but now I want to transition to using jQuery. Below is my JavaScript code: var output1 = docum ...

Adjusting image width using jQuery

I have been experimenting with creating a Webgl hover effect for an image. The effect works well, but now I am trying to specify a width for the image within jQuery. new hoverEffect({ parent: document.querySelector('.ticket'), intensity1: 0. ...

The history.push function seems to be leading me astray, not bringing me back

Issue with History.Push in Register Component App function App() { const logoutHandler = () =>{ localStorage.removeItem("authToken"); history.push("/") } const [loading, setLoading]= React.useState(true) useEffect(()=>{ ...

Experiencing difficulty in parsing the JSON document

I am struggling with reading a .JSON file (todo.json) in my Angular.Js project. The file is stored on the server, and all static files are saved within the 'public' folder of my basic Express server. Even though I can access the todo.json file di ...

The method OnJSAlert in WebChromeClient is failing to execute

I am currently working with a JS script in a WebView, where the script triggers an alert message to the WebView that I want to capture in my app. However, I am facing an issue where the onJSAlert method is not being called and I am unable to use the @Overr ...

Handling onclick events in Scrapy Splash: A comprehensive guide

I am attempting to extract data from the following website I have managed to receive a response, but I am unsure how to access the inner data of the items below for scraping: It seems that accessing the items requires handling JavaScript and pagination. ...

Determine whether there are three or more identical values when comparing two objects in typescript

Hello there, I am in need of some assistance as I am unsure where to begin. Any help would be greatly appreciated. Here are the two objects I have: const Questions = { five: "c" four: "c" one: "a" three: "a" two ...

Vue router is designed to maintain the state of child components without requiring them to

Encountering a strange problem with vue-router. Developed a simple CRUD app for managing users. The app includes four main views: User list and a create button Create view with a form child component that fetches field data from an API within the creat ...

Which file does require('./bar') try to load first - 'bar' or 'bar.js'?

Referencing the material found at , I came across an intriguing passage: The require function in Node.js allows us to import JSON files and C++ addon files without explicitly stating their file extensions. When no extension is provided, Node will first l ...

Developing an Addon for Firefox using XUL and JavaScript

I am interested in creating a Firefox Addon that dynamically generates a button in the webpage's DOM when a specific page like www.google.com is loaded. This button, when clicked, will redirect to another page such as www.stackoverflow.com. It is imp ...

Guide to Chrome's Document Object Model and JavaScript Reference

Does Chrome have a Javascript/DOM Reference page similar to the Mozilla Developer Network? I am curious about other websites that provide detailed information on Chrome's specific interpretations of web standards. ...

Display customized modal content in React based on specific criteria

I have a list of product partners with a "Know More" link that opens a modal. I'm trying to figure out the best way to pass props to the modal in order to display the correct partner's information. Here is the code snippet related to this functi ...

Having trouble with the JavaScript function not working on page load

I'm currently working on writing JavaScript code that will run once the child page, created using the window.open function, has fully loaded. Despite trying methods like window.onload and window.setTimeout, I haven't had any success. I even expe ...

Having trouble retrieving data from MongoDB and rendering it on an HTML page

Creating a Model Named Field.js in Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/SuperchainV1', { useNewUrlParser: true }); mongoose.set('useNewUrlParser', true); ...