How can transparency be adjusted in Three.js using multiple materials?

I've been working on adjusting the transparency of polyhedra that are imported using MTLLoader.js and OBJLoader.js. Below is the code snippet I am using to load a polyhedron:

// Model
var obj_file_name = file_name + ".obj";
var mtl_file_name = file_name + ".obj.mtl";
var dual_file_name = file_name + "-dual.obj";

var onProgress = function ( xhr ) {
    if ( xhr.lengthComputable ) {
        var percentComplete = xhr.loaded / xhr.total * 100;
        console.log( Math.round(percentComplete, 2) + '% downloaded' );
    }
};
var onError = function ( xhr ) { };
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'obj/' );
mtlLoader.load( mtl_file_name, function( materials ) {
    materials.preload();
    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials( materials );
    objLoader.setPath( 'obj/' );
    objLoader.load( obj_file_name, function ( object )
    {
        object.traverse(function (child)
        {
            if (child instanceof THREE.Mesh)
            {
                // Polyhedra
                child.name = "pdp-faces";
                context0.scene.add(child);
                // var geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
                // alert('From loaded OBJ: ' + geometry.vertices.length);


                // Edges
                var edges = new THREE.LineSegments(new THREE.EdgesGeometry(child.geometry), new THREE.LineBasicMaterial( {color: 0x000000}) );
                edges.name = "pdp-edges";
                context0.scene.add(edges);

                // Vertices
                var geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
                // alert('After EdgesGeometry(): ' + geometry.vertices.length);
                var vertices = [];
                var isNew;
                var tolerance = 0.0000001;
                if (geometry.vertices.length > 0)
                {
                    vertices.push(new THREE.Vector3(geometry.vertices[0].x, geometry.vertices[0].y, geometry.vertices[0].z));
                }
                for (i = 1; i < geometry.vertices.length; i++)
                {
                    l = vertices.length;
                    isNew = true;
                    for (j = 0; j < l; j++)
                    {
                        var d = geometry.vertices[i].distanceTo(vertices[j]);
                        if (d < tolerance)
                        {
                            isNew = false;
                        }
                    }
                    if (isNew == true)
                    {
                        vertices.push(new THREE.Vector3(geometry.vertices[i].x, geometry.vertices[i].y, geometry.vertices[i].z));
                    }
                }

                // Fit screen
                child.geometry.computeBoundingSphere();
                var fov = context0.camera.fov * ( Math.PI / 180 );
                var objectSize = child.geometry.boundingSphere.radius;
                var distance = 0.7*Math.abs( objectSize / Math.sin( fov / 2 ) );
                context0.camera.position.z = distance;
                context0.camera.position.x = distance;
                context0.camera.position.y = distance;
            }
        });
    }, onProgress, onError );
});

Following the loading process, I attempt to adjust the transparency using the following code:

   context0.scene.getObjectByName("pdp-faces").material.transparent = true;
   context0.scene.getObjectByName("pdp-faces").material.opacity = (1 - val/100.0);

The issue arises when dealing with polyhedron OBJ files containing multiple color faces, as this method does not effectively change their transparency.

Check out this video to see the problem in action.

Visit the program site for more information.

I would greatly appreciate any assistance or insights you could provide. Thank you in advance, Humberto.

Answer №1

If you're working with multiple materials on a renderable object in three.js, keep in mind that mesh.material will be an array. To adjust the opacity of these materials, follow this approach:

object.material[ 0 ].opacity = 0.5;
object.material[ 1 ].opacity = 0.5;

Remember to also set transparent to true for each material.

You can check if the material is indeed an array using the following code snippet:

if ( Array.isArray( object.material ) ) {

    // your code

}

This information applies to three.js version r.86

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

Vue JS Image Path

I have a Vue.js structure file that looks like this: --assets ----image ------my-image.png ------my-image2.png --components ----user ------userStart.vue To display the images using an array object, my code in userStart.vue is as follows: ...

How can I prevent receiving redundant data and effectively manage my data?

I am currently working on adding offline support to my app. The logic I am following is to first check if there is cached feed data available. If the data is present, it will set the feeds to that cached data and display it from the cache. However, it will ...

Pinia: Is it better to invoke '{myStore}' or 'return myStore' within the return statement?

I'm currently working on integrating a Pinia store into a component of my Vue app and I'm puzzled by the need to return the store in { } instead of just returning it as is. Can someone clarify the distinction between return {foo} and return foo f ...

Can the parent document interact with Shadow DOM elements?

When it comes to user-created shadow DOM elements, this question focuses more on accessibility using the date input type: For instance, let's say there is a date input on a webpage. After some editing, the shadow DOM markup for this element (in Chrom ...

How can you nest a map within a map in JavaScript?

Here is the code snippet I am working with: _renderChannels() { return this.state.channelsData.map(channelData => { return this.state.channelsStreamData.map(channelStreamData => { return <Channel channelData={channelData} ch ...

How can we enable a sitemap for web crawlers in a nodejs/express application?

Looking to enable sitemap for web crawlers in nodejs/express? I am trying to figure out where I should place my sitemap folder/files within the application flow and how to allow access for web crawlers. Currently, when visiting domain/sitemap/sitemap.xml, ...

When it comes to deploying middleware, accessing cookies becomes more challenging. However, in a local setup, Next.js allows middleware to

I have set up a NextJS frontend application with a backend powered by NodeJS and ExpressJS. Authentication and authorization are handled using JWT token-based system, where the backend server sets the token and the frontend server validates it to grant acc ...

Does Ext js have a monochromatic theme of blue running through everything

While the blue color may give off a nice office ambiance, it's important to have variety in the appearance of different applications. Is it simple to customize the look in ext js? ...

Exploring HTML5 video playback in AngularJS

When I use this code: <video id="video" class="video-js vjs-default-skin" controls width="640" height="264"> <source src="http://localhost:3000/files/public/photos/Let-her-go.mp4" type='video/mp4' /> <p class="v ...

acquiring JSON information from different domains

I am in need of creating an ajax request to fetch JSON data from a RESTful Web Service that is hosted on a different domain (KARAF using cxf). The client making the ajax call is situated on a separate domain (Apache Tomcat). The Web Service responds with ...

Data from HTML not being transferred by Angular Forms

I am facing an issue with transferring input data from HTML's <select> element to Angular Forms. Let's take a look at my code first. File Name: home-page.component.html <form [formGroup]="rForm" (ngSubmit)="addPaste(rForm.value)"> ...

Delete the selected background color from custom drop-down lists in versions of Internet Explorer 9 and earlier

In my asp.net application, I have a dropdown element. I am trying to remove the default blue background color that appears when the dropdown is selected, as shown in the image below. I have tried all the solutions provided in this link, but none of them s ...

Having Trouble Accessing Custom Screen in React Navigation?

The navigation from the Order screen to the Home Screen is not working as expected. Every screen in the route works, except for the Home screen, which just navigates back to the Map screen. I have clearly instructed to navigate to Home. Here is the curren ...

What is the best method for retrieving all input fields within a form that are of the types text, password, file, textarea, and selectbox?

Is there a way to retrieve all input fields of specific types within a form using jQuery? jQuery("#signup-form").find('input').each(function(index, element) { }); I am aware that I can target text boxes with: jQuery("#signup-form").find(&apos ...

Is this included in the total number of reads?

Following my query with CollectionsGroup, I attempted to retrieve the information of the parent's parent like this: db.collectionGroup('teams').where('players', 'array-contains', currentUser.uid).get().then(function(snaps ...

The ReactDom reference is not defined when working with React and webpack

After following a tutorial on React and webpack from jslog.com, I encountered issues with using updated syntax such as using ReactDom to call render instead of the deprecated 'React.renderComponent'. I tried running: npm install --save react-do ...

Retrieving Information from Website Database

My goal is to import data from a web query into Excel. However, I am facing a challenge with the IP address (e.g., 10.10.111.20) because it only displays page 1 with 20 rows of entry data. When I try to navigate to page 2 or beyond, the data does not updat ...

Is there a jade plug-in available that enables manipulation using syntax similar to jQuery?

If I have a list of li elements and I want to use JavaScript to find an element with class X and modify some of its attributes, I know it can be done with regular JavaScript, but I'm unsure of how to select existing elements and manipulate them. Is th ...

Personalizing Vuetify Calendar: Modifying the default Day Label Header

Exploring the Vuetify calendar for appointment scheduling has been a unique experience. Despite attempting to modify the default header using slots, I have not achieved the desired outcome. My goal is to customize it to resemble the design showcased in thi ...

Conditionals in ng-class Syntax

I'm attempting to apply a class conditionally to an element, but I'm struggling with the correct syntax. I've experimented with the code below, but it's not functioning as expected: ng-class="{foo: bar === "true"}" The value of bar i ...