Fade in/out or apply opacity to a three.js object

I'm working on a graphical web project using three.js.

I have many circles scattered like this.

https://i.sstatic.net/y4FN8.png

I'm curious if the opacity of objects can be reduced as the distance between the object and camera increases (fade out). Is it also possible to increase the opacity as the distance decreases (fade in)?

I tried looking for answers in the documentation (

https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene
), but couldn't find a clear explanation.

Does anyone know how to achieve this effect?

Thank you.

Answer №1

Modifying the transparency based on camera proximity with an object is not directly supported by the default materials in three.js. However, you can customize the fragment shader of a material to achieve this effect by adding the following code snippet:

gl_FragColor.a *= pow( gl_FragCoord.z, f );

In the demo below, I have altered the MeshNormalMaterial using onBeforeCompile(). The concept is to gradually decrease the opacity as objects approach the camera. You can adjust the transition effect using the variable f, where a higher value signifies objects becoming transparent sooner.

let camera, scene, renderer;

init();
animate();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 50;

  scene = new THREE.Scene();

  const geometry = new THREE.BoxBufferGeometry(2, 2, 2);
  const material = new THREE.MeshNormalMaterial({
    transparent: true
  });

  material.onBeforeCompile = function(shader) {

    shader.fragmentShader = shader.fragmentShader.replace(
      'gl_FragColor = vec4( packNormalToRGB( normal ), opacity );',
      [
        'gl_FragColor = vec4( packNormalToRGB( normal ), opacity );',
        'gl_FragColor.a *= pow( gl_FragCoord.z, 50.0 );',
      ].join('\n')
    );

  };

  for (let i = 0; i < 1000; i++) {

    const object = new THREE.Mesh(geometry, material);
    object.position.x = Math.random() * 80 - 40;
    object.position.y = Math.random() * 80 - 40;
    object.position.z = Math.random() * 80 - 40;
    object.rotation.x = Math.random() * 2 * Math.PI;
    object.rotation.y = Math.random() * 2 * Math.PI;
    object.rotation.z = Math.random() * 2 * Math.PI;
    object.scale.x = Math.random() + 0.5;
    object.scale.y = Math.random() + 0.5;
    object.scale.z = Math.random() + 0.5;
    scene.add(object);

  }

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

  new THREE.OrbitControls(camera, renderer.domElement);

}

function animate() {

  requestAnimationFrame(animate);
  renderer.render(scene, camera);

}
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="46322e3423230676687775776875">[email protected]</a>/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98d918b9c9cb9c9d7c8cac8d7ca">[email protected]</a>/examples/js/controls/OrbitControls.js"></script>

Answer №2

I have created a demonstration where you can establish a function to determine the opacity based on the distance between the camera and mesh. The closer they are, the higher the opacity will be. Here is the formula I used:

opacity = -1/400*distance

Make sure to set transparent to true and update the opacity every frame. Check out my sample.

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 methods can I use to minimize the frequency of the blue box appearing around text?

I successfully developed code that enables user interaction with text, triggering the opening of a modal box when clicked. In this modal box, the text turns red upon clicking, indicating activation of a checkbox. However, I notice that every time I intera ...

External JS file not executing function in AJAX response (only runs when function is directly included in AJAX response)

My issue involves an AJAX response not executing a simple jQuery function that is located in an external JS file. The function only runs when its code is directly placed within the AJAX response view. The page containing a link for dynamically loading AJA ...

Ways to center your attention on the Textbox

I am currently developing a chat program using JavaScript, HTML, and CSS. How can I set the focus on the input field for typing messages? Is it usually done with CSS code? Here is the current CSS styling for my message input field: Code: #messageField ...

Using Jquery to trigger a function with varying parameters by clicking on multiple buttons

I have a query about extracting values from input text fields in my code. Is there a solution for this issue? <?php for ($i=0;$i<3;$i++){ echo ('<input type="text" class="form-control" name="vec" id="vec'.$i.'" value=" ...

Implementing JQuery to Traverse Through JSON Data in AJAX Response

I am currently working on an AJAX call that retrieves JSON data from a query: <script> function retrieveTrips(){ // Fetching the history of trips $.ajax({ url:'cfcs/mileagedata.cfc?method=getTrips&returnform ...

What is the process for advancing an object in Three.js?

Does anyone know how to advance the position of an object in Three.js? I've been thinking about converting rotation.x, y, z into a vector and manipulating it that way. However, as a beginner, I'm unsure of how to proceed. Any guidance would be g ...

What is the best way to display every comment and response using console.log()?

Currently, I am developing a commenting system where users can leave comments and reply to existing comments. In the MySQL database image Both images depict the same scenario. In my highlighted text in yellow, it should read comments[0] instead of comment ...

Customize Button Colors in Bootstrap 4

I'm encountering difficulties when attempting to change the color of the buttons labeled "Print," "Excel," and "PDF". Despite referring to a guide, I wasn't able to succeed. The provided test case differs from my code but shares the same CSS and ...

What is the best way to organize a massive file over 10Gb filled with words?

I've been presented with this interview query: You have an input file containing words (which could be a jumble of letters) separated by commas, and the file size is 10 GB or more. Can you devise an algorithm to sort all these words? Keep in min ...

Easy steps to automatically disable a checkbox once the expiration date has been reached

I have this PHP code that retrieves values from my database. I want to prevent users from selecting or modifying items with expired dates. Could you assist me with this? The code below currently displays 'Expired' and 'Not Expired' on ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

Is it possible to establish a default URL for the expect() function?

One of the challenges I'm facing is with my Restangular call, which has a baseUrl configured in a specific file as http://localhost:3000/. For example, a call like: Restangular.all("awards").customPOST(award) Actually makes a request to baseUrl+"awa ...

Bar chart in Highcharts vanishing following the update from version 10.2.1 to 10.3.1

I've been in the process of updating my highcharts to the latest version, but I've hit a roadblock. Specifically, I have a bar chart set up with the following configuration: { chart: { type: 'bar', ...

The Vue.js scripts and styles declared in the index.html file seem to be malfunctioning

I acquired a theme that includes html, css3, and js files, and I included the file path as shown below: <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Porto - Responsive HTML5 Te ...

looking to display the latest status value in a separate component

I am interested in monitoring when a mutation is called and updates a status. I have created a component that displays the count of database table rows when an API call is made. Below is the store I have implemented: const state = { opportunity: "" } ...

The event listener for the hardware back button in $ionicPlatform is being triggered repeatedly

Encountering a glitch with the back button being triggered multiple times. While I'm in the "messages" $state, everything functions normally when hitting the back button. var messageIsClosed = true; $ionicPlatform.onHardwareBackButton(function(even ...

Issue with Jquery plugin malfunctioning on dynamically loaded elements via Ajax requests

Description: I'm currently working on a project where I need to load elements with expiration dates pulled from my database. To achieve this, I am using a Jquery plugin that relies on the HTML5 Data Type Attribute for setting the "end date". Everythin ...

The dynamic JavaScript in Bootstrap 4 seems to be malfunctioning, despite working perfectly in Bootstrap 3

I am currently implementing a dynamic modal feature using the code snippet below: // Show Ajax modal with content $(document).on('click', '[data-modal]', function (event) { event.preventDefault(); $.get($(this).data('moda ...

Rendering Based on Conditions in React Native

I'm a beginner in the world of React Native and coding and I'm looking to display text based on certain variables (as shown below). If isPlayer === true && base.length === 1, then display x Else if isPlayer === true && base.leng ...

Troubleshooting Axios Error while Sending Data in MERN Stack Application

In my development setup, I'm testing model validation specifically for the length of a name variable. The front-end is configured at http://localhost:3000/ using React + axios, while the back-end utilizes express + node. To enable communication betwe ...