Blending two materials in THREE.js on a single mesh with depth control

I'm looking to apply two different materials to a single mesh named "mesh1."

mat1 will be red in color, while mat2 will be blue.

The distance between the camera and the mesh is set at "1 unit."

When mesh1 is close to the camera (between 0.1 and 0.4 units), it will appear red. However, when it's far from the camera (between 0.6 and 1 unit), it will appear blue. During the transition phase (from 0.41 to 0.59 units), the depth will control the gradient shift from red to blue on the object.

Answer №1

To achieve a unique visual effect, you can manipulate the color of a material based on the distance between the camera and the mesh in your scene. Here is a sample code snippet that demonstrates this concept:

var camera, scene, renderer;
var mesh;

var speed = 0.0005;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 1;

    scene = new THREE.Scene();

    var geometry = new THREE.BoxGeometry( 0.1, 0.1, 0.1 );
    var material = new THREE.MeshBasicMaterial();

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

}

function animate() {

    requestAnimationFrame( animate );

    mesh.position.z = Math.sin( performance.now() * speed );
        
    var d = mesh.position.distanceTo( camera.position );
        
    if ( d < 0.4 ) {
        
        mesh.material.color.set( 0xff0000 );
        
    } else if ( d > 0.6 ) {
        
        mesh.material.color.set( 0x0000ff );
        
    } else {
        
        var s = d - 0.4;
        var b = s / 0.2;
        var r = 1 - b;
            
        mesh.material.color.setRGB( r, 0, b );
        
    }

    renderer.render( scene, camera );

}
body {
      margin: 0;
}
canvas {
    display: block;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57233f25323217677966666e7966">[email protected]</a>/build/three.js"></script>

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

Merging SCSS and CSS into a unified file using WebPack

Trying to grasp webpack as a beginner is proving to be quite challenging for me. I'm struggling with the concept of merging multiple scss and css files together using webpack, after transpiling the sass. Unlike gulp, where I could easily transpile sa ...

Choose a Different Value for Another HTML Element's Class

Is there a way to preselect an option on another page before it loads? Consider two pages, A and B. If a user clicks a button on page A, I want the default option on page B to be changed to "something" before redirecting them. How can this be achieved s ...

What if I am fine with receiving the error message 'Cannot read property **** of undefined'?

Here is some code that I am working with: $scope.query.toLowerCase() != 1 When the query is not defined, an error appears in the console. Surprisingly, the code still functions as intended despite this error. What is the best way to handle this situatio ...

JS: Ensuring Cross-Browser Compatibility - my JavaScript code functions correctly in Chrome but experiences issues in Firefox

I am facing an issue with my JavaScript code that works perfectly in Chrome but not in Firefox. I lack the experience to troubleshoot this problem on my own and would appreciate some assistance. I tested the code both locally on my development machine usi ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

When attempting to use AJAX to send an object from JavaScript to PHP on the same page, I encountered an issue where, instead of receiving just the object, the entire HTML page was being returned

When I make a POST request, instead of receiving the object as response data, I am getting the entire HTML page back. This is causing me to be unable to retrieve the object in my PHP script. //Here we have an example of the object, not the actual object ...

Once the timer has finished, I would like for a specific component to be displayed

I am trying to make my component CountDownSquare disappear once the timer has fully counted down. In my homePageData, I have the main text stored in a h3 element that should only appear once the countdown is complete. I attempted to use a ternary stateme ...

Error encountered: Unexpected character 'C' found at the beginning of the JSON data

Hey there, I'm new to all of this so just trying to figure it out! :) I stumbled upon a GitHub project that I really want to work on and understand in order to create my own solution. The project can be found at the following link: https://github.com ...

Populate the table with JSON content using jQuery

I am attempting to populate a table with JSON data using jQuery, but the content within the div remains empty. I need assistance in identifying the error. The array list contains the data (I verified this using console.log(list)). Additionally, list[' ...

Bring in a function by its name from the ts-nameof package that is not declared in the d.ts export

Recently, I came across a captivating package that caught my interest and I would love to incorporate it into my TypeScript application: https://github.com/dsherret/ts-nameof However, upon attempting to import the nameof function, I realized it was not be ...

What is the best way to apply typography theme defaults to standard tags using Material-UI?

After reading the documentation on https://material-ui.com/style/typography/ and loading the Roboto font, I expected a simple component like this: const theme = createMuiTheme(); const App = () => { return ( <MuiThemeProvider theme={theme}> ...

The functionality of JQuery TableSorter is not responsive when a user clicks on it

I seem to be running into an issue on my website where I can't get the JQuery TableSorter to work properly. When I attach it to a table for sorting, nothing happens when I click on the headers. The table remains static and unsortable. Here's a s ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Deactivated a specific radio button with a particular class attribute

Is there a way to disable radio buttons with a specific class using JavaScript? I attempted the following code: if( $("input[type=radio]").hasClass("class-full") ){ $(this).attr('disabled', true); } However, it does not seem to be effective ...

Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jqu ...

Tips for creating Angular unit tests that involve setting @Input values and mocking them

As a beginner in Angular, I am currently diving into writing test cases. How can I approach writing unit tests for the following code snippet in Angular/TypeScript? @Input() set myOutputData(res: any) { this.apiError = ''; if (!re ...

Changing the size of text in jquery for selected text can be done using the resize

Is there a way to change the font size of text within a specific div when it is selected by the user? I have the JavaScript code, but I need to resize the font size of the focused or currently selected div only. $("#slider").on("change",function(){ ...

Executing Datalist's Delete Command through Page Methods Implementation

Recently, I came across an issue with my DataList and Update Panel on my webpage. I noticed a significant delay in response time after incorporating the Update panels... intrigued, I delved deeper into this phenomenon and found some interesting insights in ...

Interact with multiple databases using the singleton design pattern in a Node.js environment

I need to establish a connection with different databases, specifically MongoDB, based on the configuration set in Redis. This involves reading the Redis database first and then connecting to MongoDB while ensuring that the connection is singleton. Here i ...

Enhancing Javascript with ES6 for nested for loop operations

Hey there, I have a question about converting a nested for loop into an Array map/ES6 way. How does that work when dealing with nested for loops? for (var i = 0; i < enemy.ships.length; i++) { for (var n = 0; n < enemy.ships[i].locat ...