Changing the color of a single child object in Threejs

Hey there, I'm facing an issue with changing the color of a specific element in my 3D Model (imported using the GLTFLoader). I've included some images showcasing the model's structure.

The element I'm trying to target is the one highlighted in red. The path to this element is:

children[0].children[31].children[10].children[1]

https://i.sstatic.net/KPq7Y.png https://i.sstatic.net/5cwFn.png

Whenever I try to change the color using the material property, other elements in the object that share the same color (in this case white) also turn red.

This object was exported using Siemens NX. I believe the issue lies in the structure of the 3D Model. The children elements lack specific names, making it difficult to manipulate them individually. Moving forward, I plan to assign names to the object elements. Does anyone else work with NX and how do you organize objects to make working with Three.js easier?

Answer №1

When I modify the color in the material property, all elements of the object sharing the same color (white in this case) automatically switch to red.

This behavior is likely due to these objects utilizing the same material. To prevent this, consider duplicating the material before adjusting its color property. By following this approach, you can modify the color without affecting other objects.

const clonedMaterial = object.material.clone();
clonedMaterial.color.set(0xff0000);
object.material = clonedMaterial;

Answer №2

After spending a couple of days grappling with this question, here is my perspective on it. While I may not be an expert, my response is based on my efforts to modify a color within a specific section of the resulting GTLF/GLB file.

// Traverses through the scene objects' children and parents.
const SetColorTEXTURE = (c) => {
  console.log('BREAK1', c);
  Viewer.scene.traverse(function (child) {
    console.log('BREAK2C ', child)
    if (child.name.includes('XXXXXX-PCB-XXX-XXXX')) {
      for (const i of child.children) {
        console.log('BREAK2B ', i)
        if (i.isMesh) {
          console.log('BREAK2A ', i)
          i.material.color = new THREE.Color('rgb(212,175,55)');
        }
      }
    }
    if (child.isMesh) { ...

My observation led me to realize that the STEP file I was working with lacked the necessary grouping and setup for two key aspects.

  1. The issue of grouping the children, each carrying their own unique styling tied to the MaterialStandardMesh namespace, became apparent. I faced challenges in styling a specific Mesh because the parent held the top-level namespace with a name of "". This lack of clear hierarchy made it difficult to apply individual styles or textures to that particular item.

Looking at how the Mesh is structured in the console for a specific item, four distinct parts are noticeable. 1. A parent: Group with a name of "", linked to a parent: scene named xx-scene, representing the main scene.

The 3. material: MeshStandardMaterial bears an empty name, further complicating the matter, as elaborated in the subsequent point.

Essentially, everything stems from the parent: Group and Scene, forming a tree structure that ties back to the main parent/scene, xxx-scene depicted in the image below.

Scene
  |
  -- Group
  |
  -- PerspectiveCamera 
  1. Given this setup, there are two ways to isolate a specific item in the GTFL/GLB file. One approach involves the previously discussed information. An example is presented below. The other method entails creating and naming specific material: MeshStandardMaterial properties.

Referencing items 3 and 4 in the diagram, it is evident that the lack of property naming leads to an empty namespace, resulting in uniform color/texture application across the main scene. Without distinct parent-child or material classification, separate styling proves challenging.

Consequently, cloning fails to address the issue effectively, as it perpetuates the same problem without potentially creating a new scene structure. This method did not yield the desired results in my case.

https://i.sstatic.net/D51TI.png

The code snippet above demonstrates my attempt to validate a theory by isolating a child within the parent scene. By doing so, I successfully targeted all the Mesh elements for that child, altering their properties exclusively.

In the console screenshot below, a child of the parent connected to the Scene holds its own Object3D and Mesh. Despite lacking specific material properties for each Mesh, I managed to modify the particular item successfully.

https://i.sstatic.net/XEr2g.png

The subsequent image showcases the application of three different colors using the provided code snippet and the traversal mechanism of the Viewer.scene.Traverse method.

https://i.sstatic.net/PgKmz.png

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

What is the best way to delete table rows based on their assigned class?

Within my HTML document, there is the following structure: <table id="registerTable"> <tr class="leaderRegistration"> <!--table contents--> </tr> <tr class="leaderRegistration"> <!--table conten ...

Having trouble with ReactJS: Why is this.setState not working?

Hello there, I am currently learning ReactJS and struggling with an issue where I keep getting the error message "this.setState is not a function". constructor() { super(); this.state = { visible: false, navLinesShow: true }; ...

Retrieve the expansive offset label for a time zone utilizing moment-timezone

The luxon library enhances the ability to retrieve the offsetNameLong based on the timezone ianaName, which gives a localized translated zone name. For example: DateTime.local().setLocale("en-US").setZone("America/Los_Angeles").offsetNa ...

Express: utilizing rawBody or buffer for a specific endpoint

I am looking to access the rawBody (buffer) specifically for a POST request on one route within my application. Currently, I have the following code snippet in my app.js: app.use(bodyParser.json({ verify: function(req, res, buf) { req.rawBody = buf; }})) ...

Monitor the collection for changes before adding an item to the collection

When using ui-select multiple, I am facing an issue where I need to check the collection before ng-model="collection" is updated in order to ensure that the new value is not already present in it. Simply watching the collection does not solve this problem ...

The onclick event seems to be malfunctioning on the website

My goal is to implement a modal box that appears when a user clicks a button and closes when the user interacts with a close button within the modal box. I have created two functions for this purpose: check() : This function changes the CSS of an element ...

What is the simplest way to extract only the error message?

Having this code snippet. $('div#create_result').text(XMLHttpRequest.responseText); If we look at the content of XMLHttpRequest, it shows: responseText: Content-Type: application/json; charset=utf-8 {"error" : "User sdf doesn't exist"} st ...

Update DataTable 1.9 while preserving existing rows

I'm currently using dataTables js version 1.9 Periodically, an ajax call is made to the server to retrieve information that should be displayed in a table every 60 seconds or so. Although I can easily clear and repopulate the table like this: $(id) ...

Locate the closest pals near my present whereabouts

Is it possible to find my friends by obtaining their location from their mobile phones when they are near me? I have a code snippet below with the variable cities where I can input the numbers of my friends. Can I achieve this or do I need to make some m ...

Implementing a loading animation effect using AJAX that requires a loop delay and sleep functionality

My jquery ui dialog is loaded via ajax with a partial view from the server. Initially, the dialog opens as a dialog-ajax-loader and then animates/grows to fit the content once the call returns. The issue arises when the dialog content gets cached or the a ...

Is it possible to change the name of a PHP file using the value entered in an input

I am currently in the process of trying to change the name of a file while uploading it using the JQuery uploader. I have made some progress, and here is the crucial part of my UploadHandler.php: protected function handle_file_upload($uploaded_file, $name ...

"Encountering a problem with a missing object in jQuery when referencing

I'm encountering an issue with jQuery's $(this) object that's causing me to lose track of the this element in my code: $('.star').click(function (){ var id = $(this).parent().attr('id').split('rating')[ ...

Is it possible to successfully pass a parameter from a servlet to a JavaScript function, but encounter issues when trying to view the database

In my view servlet, I am displaying user data from the database in a table. Each row of the table has buttons that allow users to change the cells in that row to text boxes. The issue I am encountering is that when I retrieve the data and loop through to ...

The blender model that was imported into the three.js scene appears to be lacking color

I have created a tree model in Blender and exported it for use in Three.js. However, when I load the model in my scene, it appears only in black and white. Can you advise on the correct method to ensure that the model displays with its original colors? .j ...

Struggling with updating the background color of multiple HTML elements with the same class in real-time

I'm facing an issue with dynamically updating background colors of specific elements using ajax, JSP, and a servlet call. Even though all the lines of code seem to be executing, there is no visible change on the front end. I've attached my JS fun ...

What is the process for combining AngularJS filters?

I currently have a fragment object like this: [{id: 721, titulo: "Cotizador Gastos Médicos Bx+ 2019", descripcion: "Cotizador Gastos Médicos Bx+ Tarifas 2019", updateDate: "2020-03-25 14:30:22.0", idCategoria: "1", …}, {id: 88, titulo: "Cotizador GMM ...

Element not producing output via Autocomplete from mui/material package

My challenge involves handling an array of states within the Autocomplete component. Once a state is selected, a corresponding component needs to be rendered based on the selection. However, despite successful state selection in the code, nothing is being ...

Receiving an error while trying to install packages from the NPM registry due to non

I am facing some challenges while attempting to install my Ionic App through the registry along with its dependencies. I have been using npm i --loglevel verbose command, and my ~/.npmrc file is configured as follows: //nexus.OMMITED.com/repository/:_auth ...

What is the best way to align text extracted from an API using JavaScript?

I'm currently exploring content generation through APIs, but I'm facing an issue where the text generated is not aligning properly within the container on the screen. The main problem lies in getting the card to be centered on the screen with al ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...