Enhance the texture in Three JS by incorporating specularity for a shiny effect

When working with textures in three.js, I often find myself wanting to add some specularity or shininess to my objects. While browsing examples, I come across code snippets like this:

new THREE.MeshPhongMaterial( { 
    color: 0x996633, 
    specular: 0x050505,
    shininess: 100
} );

However, my own code looks quite different:

// Applying a texture
var texture = new THREE.Texture();
var imgLoader = new THREE.ImageLoader( manager );
imgLoader.load( 'assets/uv.png', function ( image ) {
    texture.image = image;
    texture.needsUpdate = true;
} );

// Loading the model
var loader = new THREE.OBJLoader( manager );
loader.load( 'assets/obj.obj', function ( object ) {
    object.traverse( function ( child ) {
        if ( child instanceof THREE.Mesh ) {
            child.material.side = THREE.DoubleSide;
            child.material.map = texture;
        }
    } );
    object.position.y = - 95;
    scene.add( object );
}, onProgress, onError );

I am unsure about how to incorporate the shininess and specular settings into my current setup because I am not utilizing a THREE.MeshPhongMaterial. If I were to switch to THREE.MeshPhongMaterial, I'm uncertain how to integrate it with THREE.texture.

Answer №1

One way to customize the appearance of an object is by overriding its material upon loading.

var loader = new THREE.OBJLoader(manager);
loader.load('assets/obj.obj', function (object) {
    object.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
            child.material = new THREE.MeshPhongMaterial({
                color:     0x996633, 
                specular:  0x050505,
                shininess: 100,
                map:       texture,
                side:      THREE.DoubleSide
            });
        }
    } );
    object.position.y = - 95;
    scene.add(object);
}, onProgress, onError);

Answer №2

When working with three.js, you have a variety of materials to choose from, each with different properties for customization (check out some examples here). If you're aiming for a glossy look, options like MeshStandardMaterial or MeshPhongMaterial would be suitable. The documentation provides details on how to configure these materials.

MeshStandardMaterial can be considered a more advanced version of MeshPhongMaterial, offering greater accuracy in terms of physics but requiring more computational resources. On the other hand, MeshPhongMaterial serves as a good approximation.

One important aspect to note is that material replacement is possible by simply assigning a new material to an object. For instance:

if ( child instanceof THREE.Mesh ) {
    var oldMaterial = child.material;
    child.material = new THREE.MeshStandardMaterial({
        side: THREE.DoubleSide,
        map: texture
        // ..copy necessary properties like color from oldMaterial if needed
    });
}

This code snippet demonstrates how to completely switch out a material for another one.

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 choose a distinct element from an array?

I've been working on a task to identify the unique element within an array. I've made progress and managed to solve 95% of it, but I'm encountering an issue with one particular situation. The error message reads 'expected 0 and got 1&ap ...

Animating Buffer Geometries in Three.js

My Three.js scene displays triangles spread out over a designated area. geometry = new THREE.BufferGeometry(); geometry.dynamic = true; positions = new Float32Array(triangles * 3 * 3); const normals = new Float32Array(tria ...

The functionality of nested dynamic routing in the API is experiencing issues

Looking to extract product details from a specific category of products? My folder structure appears as follows: https://i.stack.imgur.com/1UCy3.png In "productId/index.jsx" => This snippet is utilized to retrieve individual product details: ...

Clicking on the search box will remove the item that is currently displayed

Currently, I am working on creating a dropdown menu that includes a text box. The goal is for the items to appear when the text box is clicked, and for the selected item to turn green once clicked and then display in the text box. I'm interested in fi ...

Error encountered while attempting to cast value "xxxxxx" to ObjectId in the "item" model, resulting in a CastError

I've been struggling to resolve an error while trying to delete a todo from a page using findByIdAndRemove and findByIdAndDelete methods. Despite researching and attempting various solutions, the error persists. Any assistance would be greatly appreci ...

MongoDB ratings are failing to update as anticipated

I'm currently working on incorporating a rating system similar to upvotes and downvotes. Users have the ability to vote on a lesson only once. They can change their votes between up and down. If they vote the same as their previous vote, it cancels ou ...

Tips for transforming JavaScript array object information based on its null key value

Below is the data I currently have: let activityList = [ { "2-createdAt": "2019-12-27T13:11:04.300+0000", "2-modifiedAt": "2020-01-02T13:28:18.877+0000", "2-createdBy": "admin_tna", "2-lastModifiedBy": "admin_tna", "2-id": 2, "2-name": "Activity 2", "2- ...

Tips for making a multiselect dropdown menu using bootstrap

I am working on a JavaScript application that parses data and displays it to users in a table generated by JavaScript. I am looking for a simple way to allow users to choose which fields to display in the table using a dropdown list or something similar. I ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

Is it possible for me to alter the script for my button's onclick

Is there a way to replicate all properties of a div when creating a clone using JavaScript code? I have an existing script that successfully creates a clone of a div when a button is pressed, but it does not copy the CSS properties. How can I ensure that t ...

angular8StylePreprocessorSettings

I'm currently trying to implement the approach found on this tutorial in order to import scss files through stylePreprocessorOptions in Angular 8. However, I'm encountering an error stating that the file cannot be found. Any suggestions on how to ...

Is there a way to modify this JavaScript code so that it can function with a

I have developed a unique audio player that plays random sections of different songs. Currently, it is hardcoded for one song with three intros, a midsection, and three outros. I am looking to create a system where a list of songs can be randomly chosen fr ...

Interactive state for associated product within list without order

I am currently working on a project that involves an unordered list with separate list items. The menu design includes product images in the top list item and the corresponding product names in the list item below. I have successfully implemented a hover s ...

What is the best way to transfer the http server variable between different layers in node.js without requiring it in a separate file?

I've developed a nodeJS application that involves creating a server in the file server.js. The code looks like this: http.createServer(app).listen(app.get('port'), function (err) { if (err) { console.error(err); } else { ...

Mouse over the image to reveal a fresh window

I'm attempting to achieve a similar effect to that of this website (you may need to register to view it). Here's the image that illustrates it: As you can observe, when I hover over the image, a box appears and then when I hover over the YouTube ...

Adjust the divs right element by adding or removing 1 pixel for every size change in the browser

I have been exploring different approaches to achieve this task and it seems like using javascript might be the most effective way. I am currently dealing with a stubborn social icon container placement issue. More details on my previous question can be fo ...

Is there a way to dynamically adjust @keyframes properties through JavaScript?

I am looking to dynamically change the top value of the keyframes based on a JavaScript variable x. While I have experience changing CSS with JavaScript, this particular challenge has me stumped. Code: var x = Math.floor((Math.random() * 1080) + 1); ...

Troubleshooting NodeJS CORS issue with heavy requests for file uploads

I'm currently working on a project that involves an Angular front end and a NodeJS API deployed in production using AWS services like S3 and Elastic Beanstalk. When attempting to upload images, I encounter a CORS error if the image is too large or wh ...

What is the best way to measure the distance between two countries, between a country and a city, and between two cities?

What is the best method for determining the distance between two countries, between a country and a city, and between two cities? ...

Changing a PHP object into an array

I've searched for solutions on various platforms, but my situation presents a unique challenge. In my PHP charts factory, I am passed an array of strings like: $charts = ['SomeChart', 'SomeOtherChart', 'AndAnotherChart' ...