Having difficulty altering the color of an element in Viewer

Currently, I am conducting a PoC and experimenting with changing the color of a selected element to red. Despite creating a class as shown below, I am facing issues where the elements do not change color when selected. I have attempted various examples from different sources on the internet, but unfortunately, none of them seem to work.

Is there a way to modify the color of a specific element (either using dbId or fragId)? I have been unable to find comprehensive API documentation for this in the Forge API, so I am somewhat navigating in the dark.

/* global Autodesk */

import * as three from "three";
import * as uuid from "uuid";

type SelectionChangedEvent = {
    fragIdsArray: number[];
    dbIdArray: number[];
    nodeArray: number[];
    model: object;
};

export default class ViewerInteractionHandler {
    viewer: Autodesk.Viewing.Private.GuiViewer3D;
    material: THREE.Material;

    constructor(viewer: Autodesk.Viewing.Private.GuiViewer3D) {
        this.viewer = viewer;
        viewer.addEventListener(
            Autodesk.Viewing.SELECTION_CHANGED_EVENT,
            (e) => this.handleSelectionChange(e)
        );
        this.material = new three.MeshStandardMaterial({
            name: "CustomMaterial",
            color: 0xFF0000,
        });

        this.viewer.impl.matman().addMaterial(uuid(), this.material, true);
    }

    async handleSelectionChange(event: SelectionChangedEvent): Promise<void> {
        this.changeMaterialsForFragments(event.fragIdsArray);
    }

    changeMaterialsForFragments(fragIdsArray: number[]) {
        fragIdsArray.map((fragId) => {
            this.viewer.model.getFragmentList().setMaterial(fragId, this.material);
        });
        this.viewer.impl.invalidate(true);
        this.viewer.impl.sceneUpdated(true); // not sure which it is, trying both
    }
}

Answer №1

Give viewer.setThemingColor a shot - check out the documentation [here] ():

viewer.setThemingColor( dbId, color:THREE.Vector4, [, model [, recursive:boolean ] ] ) //starting from Viewer v6.3 you may recursively apply color to child nodes

To remove them, use viewer.clearThemingColors

UPDATE:

Check out the live example here

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

Creating an array inside a Vue function

Currently, I am facing a challenge with restructuring an array in Vue.js. I am able to log the values within my method and push them into an array, but I'm struggling to format the array as required. The desired structure of the array should be like ...

Utilizing formData.append in TypeScript to handle arrays

Hey there! I'm facing an issue while trying to send a form to my Profile endpoint. The problem lies in the 'user:{}' field, as I am unable to properly insert my array data into this specific field. Here is a breakdown of the fields within m ...

Issue: Experiencing multiple re-renders when attempting to send a post request to the backend using

export default function CRouter() { const [token, setToken] = useLocalStorage('auth', '') const [user, setUser] = useState(false); const GetUser = () => { if (token !== "" && !user) { axios.post(&apo ...

Unconventional JavaScript Variable Declaration

While going through some source code, I stumbled upon this peculiar variable declaration that has me a bit confused. let eventsEnabled : ?boolean = null; Can someone explain what exactly this means? You can find the source code here. ...

Need to know how to invoke a function from an http callback function that resides in a separate file? Simply use the `app.get("/", callbackFun)` method

Directory Organization: testAPI contactDetail dispMobNo.js myModule.js index.js index.js const express = require("express"); const app = express(); const port = process.env.port || 3000; const getCustNo = require("./cont ...

Utilize the split functionality only when the character you want to split by is found in

Consider the following situation: I have 6 string variables that contain special characters. I stored these 6 strings in an array like this: arr=[str1,str2,str3...); arr=escape(arr); due to the presence of special characters in some string variables. ...

Unexpected output from the MongoDB mapReduce function

Having 100 documents stored in my mongoDB, I am facing the challenge of identifying and grouping possible duplicate records based on different conditions such as first name & last name, email, and mobile phone. To achieve this, I am utilizing mapReduc ...

Upon loading, the IntersectionObserver immediately declares the isIntersecting property true for all elements

Yesterday, when I executed this code, everything functioned as expected. The observer successfully loaded the images once they intersected the viewport: <template> <div id="gallery" class="gallery"> <div class=" ...

When attempting to open a form in edit mode, data binding fails to work across multiple form controls

When clicking on the edit button, data is loaded into the form using [(ng-model)], however, it seems to be working correctly only for some fields and not all fields. The data is displayed in only a few fields despite receiving data for all fields. Below is ...

Is there a way to extract subtitles from a javascript-controlled webpage using Python?

I am attempting to scrape information from this website: Link to Website Specifically, I am trying to extract the title ''Friday Night Lights'', but I am encountering difficulties accessing it due to JavaScript on the site. To achieve ...

Protractor never-ending cycle

In my previous question, I encountered an issue with clicking a button until it becomes disabled. Initially, the solution was as follows: var nextPage = function () { if (element(by.css('[ng-click="vm.nextPage()"]')).isEnabled()) { e ...

An error was encountered in customizing CKEditor5 in Vue: compilation unsuccessful

I tried to integrate a custom CKEditor5 into my Vue application, but encountered a failed to compile error. I generated the custom build using the online tool provided by CKEditor. Subsequently, I placed the files in a new folder called ckeditor within th ...

AJAX - Self-Executing Anonymous Function

I have a question that may seem trivial, but I want to make sure I'm heading in the right direction. I've created two different versions of an XMLHttpRequest wrapper, and both are functioning correctly. const httpRequest = function () { let ...

Issue encountered while transforming the data buffer into the video within a Node.js environment

I am attempting to create a buffer from the mp4 video, and then convert that buffer back into the video. The buffer is being generated as follows: const buffer = Buffer.from("Cat.mp4"); console.log(buffer); The output I receive is <Buffer 43 61 74 2e ...

Working efficiently with query selectors in React using useRef

I have created a typewriting effect function and now I am trying to display the code associated with this effect within a specific div element (typingRef). Currently, I am using typingRef.current = letter, but I am wondering if this is equivalent to docu ...

React Hooks encountering issues with keydown/up events functionality

Currently, I am in the process of implementing arrow-based keyboard controls for a game that I have been developing. In order to stay updated with React, I decided to utilize function components and hooks. To showcase my progress, I have put together a dem ...

"Unlocking the door: a step-by-step guide to logging in with ajax and json for your hybrid

As a beginner coder, I am currently working on a project to create a mobile web login form using json and ajax. To test my code, I followed the tutorial provided here. This is the code I have developed: <!DOCTYPE html> <html> <head> ...

Unable to transform node lacking a body

I am attempting to execute the sample code in the react-testing-library to test react hooks. However, it's encountering an issue on this particular line: testHook(() => ({count, increment} = useCounter({ initialCount: 2 }))) It appears to be rela ...

Encountered a build issue following the Svelte update: The subpath package './compiler.js' is not recognized by the "exports" definition

Challenge After updating from Svelte version 3.0.0 to the latest using npm i svelte@latest, I encountered an issue where my application would not run and constantly displayed the following error: [!] Error: Package subpath './compiler.js' is n ...

Executing Javascript on Selenium RC with PHP is a crucial skill to have in your toolkit

Is there a way to execute Javascript from Selenium RC? I have been trying different methods with no success so far. I attempted the following approach: I created a custom function in user-extensions.js: function sayhello() { document.write('hel ...