Adjust the transparency and viewability of an object loaded from OBJMTL Loader using three.js dat-gui

I have successfully loaded an object using OBJMTLLoader and now I want to be able to manipulate its position, visibility, and opacity using the dat-gui control panel. Although I have been able to move the loaded object following this example, I am having trouble changing its visibility and opacity. It seems like I need to work with the "materials" of the loaded object. I attempted to implement the solution provided in this answer, but unfortunately, it did not work. Here is the current state of my code:

objects = [];
    var loader = new THREE.OBJMTLLoader();
    loader.addEventListener('load', function(event){
        object = event.content;
        object.traverse(function(child){
            if (child instanceof THREE.mesh) {
                //The child is needed for the raycaster intersection later
            };
        });
    });
    loader.load("models/Model1.obj", "models/Model1.mtl", function (object) {
                objects.push(object);
                scene.add(object);
    parameters = {
                    x:0, y:2, z:0,
                    opacity: 1, 
                    visible: true,
                    reset: function() { resetObject() }
                };
    var folder1 = gui.addFolder('Position');
                var objectX = folder1.add(parameters, 'x').min(-200).max(200).step(1).listen();
                //.............
                folder1.open();
                // moving model is OK. Deleted to save space...

                var objectOpacity = gui.add(parameters, 'opacity').min(0).max(1).step(0.01).name('Opacity').listen();
                objectOpacity.onChange(function(value){
                object.material.opacity = value;  });

                var objectVisible = gui.addColor( parameters, 'visible').name('Visible?').listen();
                objectVisible.onChange(function(value){
                object.material.visible = value;   });

                gui.add( parameters, 'reset' ).name("Reset Object Parameters");
                gui.open();
                // and the required functions as in the example.

When I run the above code, the console displays the following errors:

Uncaught Failed to interpret color arguments //dat.gui.min.js:87
Uncaught TypeError: Cannot set property 'opacity' of undefined

Could someone guide me on how to properly adjust the visibility and opacity from the dat-gui panel? Thank you.

Answer №1

material.visible determines the visibility of the material itself, not the object it is applied to. To control the visibility of the object, you should use the Object3D.visible attribute. To make an object visible or invisible, you can set its visibility using the following code:

object.visible = value;

When it comes to materials, the loader will return a THREE.Object3D rather than a THREE.Mesh. This means you cannot directly access the material in the same way. Instead, you should iterate through the object's children to access and modify the materials like this:

object.traverse( function (child) {
    if (child instanceof THREE.Mesh) {
        child.material.opacity = value;
        child.material.transparent = true;
    }
});

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

Guide to generating a text string by utilizing the foreach loop

Is there a way to combine text strings from interfaces into a single file for display in UI? The current code is generating separate files for each interface. How can I achieve the expected result of having all interfaces in one file? Additionally, is it ...

Javascript deepmerge causes issues with objectid manipulation

While I have experience with javascript, using node.js for the first time has presented some challenges. I am attempting to form a basic query to be used in mongoose, with the intention of adding conditions later on. I am currently employing deepmerge to m ...

The act of transmitting data via a timer using JS WebRTC leads to crashes if the page is reloaded before

In one of my server.js files served by a node, I have written the following code snippet: function multiStep(myConnection, data) { var i=0; var myTimer=setInterval(function() { if (i<data.length){ var element=JSON.string ...

Shade the entire td column in different colors depending on the characteristics of th

I am working with a table and here is the code for it: <table> <thead> <tr> <th style="width: 40%; text-align: center; vertical-align: center;">Nr.<br> crt.</th> <th style="font-weight: bold; wi ...

Tips for running Scrapy and Selenium on a webpage that utilizes angular JavaScript to serve data

I have been working on a web scraper that follows this process: Visit site A -> click on the buy now button -> redirected to Amazon -> scrape data -> return to site A The issue I am facing is that the site is built using AngularJS, and I am h ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

Updating the minimum date based on the user's previous selection using React JS and Material UI

In my material UI, I have two date pickers set up: From Date - <KeyboardDatePicker value={initialDateFrom} disableFuture={true} onChange={handleFromDateChange} > </KeyboardDatePicker> To Date - <KeyboardDatePicker value={initialDateTo} ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

NodeJS: Extract images based on specified coordinates

Dealing with images that contain text can be a challenge, but by using tesseract and the imagemagick node module, I was able to extract the text successfully. The only issue I encountered was related to the image size. https://i.sstatic.net/XldZC.png For ...

Visualizing JSON data in React.js using Chart.js

Currently, as a beginner in ReactJS, I am working on an application that displays COVID-19 data from a JSON API in a visual format using Chart.js. However, despite trying various solutions, I am unable to visualize the data. Below is my source code: App ...

Finding the Right Path: Unraveling the Ember Way

Within my application, I have a requirement for the user to refrain from using the browser's back button once they reach the last page. To address this, I have implemented a method to update the existing url with the current page's url, thereby e ...

Using more than one button to activate a single Material-UI Popper component

I recently found myself in a situation where I needed to activate the Material-UI <Popper /> component from various clickable elements. According to the Popper component API on the official Material-UI website, setting the anchorEl property determine ...

Embracing Efficiency with Asynchronous Requests in a React Redux App Utilizing Redux Thunk

Challenge I am currently facing a dilemma in implementing an AJAX request that needs to be triggered by various UI elements on a webpage. The AJAX request is consistently directed towards the same endpoint and always sends identical properties from the re ...

Error message: Please provide an expression with const in React JS component

Can you assist me with this issue? I am trying to determine if the user is registered. If they are registered, I want to display the home URL, and if they are not registered, I want to display the registration URL. To do this, I am checking the saved dat ...

How can I change the colors of points on a 3D scatter plot using Three.js as I zoom in?

Seeking assistance with a project involving displaying a 3D point cloud containing approximately 200K points, akin to the image provided below, complete with a colorbar. https://i.sstatic.net/L6ho0.png We are looking to dynamically update the colorbar wh ...

What sets apart .ejs from .html files?

In my Node Js project, all front end files are in .ejs format and call the server.js for backend work. 1) Is there additional functionality provided by ejs compared to html? 2) Does this pertain to expressJs functionality in Node? 3) Can I use angularJs ...

When working within a module using node.js and three.js, you may encounter an error message stating that "document

Currently, I am utilizing an app to execute various functions that I created in another .js file, where these functions are defined to facilitate drawing objects on a canvas. app.get('/visualization.html', function(req, res) { //Setting ...

Using jQuery to dynamically select all rows (`tr`) that contain table data cells (`td`) matching

Although my title may seem confusing, it's the best I could come up with. I'm looking to identify all tr elements that contain td elements matching specific filter criteria. Here is an example: <tr class="row" id="1"> <td class="ph ...

Challenges with Vuex and updating arrays using axios

I am currently facing a challenge with VueJS Vuex and Axios: The issue arises when I retrieve an array with Axios and loop through it to populate its children this way: "Rubriques" has many self-relations, so one rubrique can have multiple child rubriques ...

Struggling to integrate Material UI (MUI) into my React application

I have followed all the necessary steps to install materialUI, emotion/react, and emotion/styled in my react app. However, I am encountering an issue where MUI does not seem to work properly. There are no errors displayed on the console or webpage, but not ...