Adjust the opacity of a MeshBasicMaterial in real-time

<script type="importmap">
    {
        "imports": {
          "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="384c504a5d5d784e0816090e0a1608">[email protected]</a>/build/three.module.js",
          "three/addons/": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccb8a4bea9a98cbafce2fdfafee2fc">[email protected]</a>/examples/jsm/"
        }
    }
</script>

<script type="module">
    import * as THREE from 'three';

    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    camera.position.z = 10;
    camera.position.x = -5;

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    const geometry = new THREE.BoxGeometry( 2, 2, 2 );
    var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    const cube = new THREE.Mesh( geometry, material );
    scene.add( cube );
     
    material.opacity = 0.2;
    material.transparent = true;

    function animate() {
        requestAnimationFrame( animate );
        renderer.render( scene, camera );
    }
    animate();
</script>

Above code is functioning properly and the opacity of the cube is changing. However, if I move the material updating into a setTimeout function, like so:

// material.opacity = 0.2;
// material.transparent = true;
var tmout = function() {
    material.opacity = 0.2;
    material.transparent = true;
}
setTimeout(tmout, 1000 );

Then the opacity is not changing. I'm wondering why the material is not changing inside setTimeout? What could possibly be incorrect here?

Answer №1

Implementing arrow function to maintain the context of 'this' within the module that is calling it. ¯\_(ツ)_/¯

import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 10;
camera.position.x = -5;
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry(2, 2, 2);
var material = new THREE.MeshBasicMaterial({
  color: 0x00ff00
});
const cube = new THREE.Mesh(geometry, material);

scene.add(cube);
material.opacity = 1;
material.transparent = true;


function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
  setTimeout(() => {
      this.material.opacity = 0.2;
      this.material.transparent = true;
    },
    1000);
}
animate();

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

Ensuring secure Firebase JSON database access through Firebase authentication

I am currently developing a mobile app using Ionic 3 with Angular, and I am utilizing the Facebook Native Cordova plugin for user login. In terms of Firebase database security, the documentation provides guidance on rules syntax like this: { "rules" ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Implement two different styles within an element's style properties

Welcome everyone, I have a question regarding adding marquee effects to a table row along with highlighting it. Is it possible to include moving text from left to right in the same active row? For example, let's say that the current time is 12:45 AM. ...

The AngularJS $HTTP loop counter fails to update

When working with an HTTP service and binding JSON data to HTML, I implemented the following code: This function uses a 2-second timer to automatically fetch data whenever there is a change in the backend. function sampleDevices ...

Are you familiar with manipulating Arrays or Objects in jQuery?

In JavaScript, we can create objects with keys as strings for similar functionality to an associate array. Check out this example here. For example: ".home-title":[ ["font-size","12px"], ["line-height","16px"], ], However, if you need a ...

Trigger JavaScript function once all Ajax requests have completed

Seeking assistance with troubleshooting JavaScript code that is not functioning as expected. The Application sends file names to the server via Ajax calls for processing, but I need to update the database once all imports are complete. The problem arises ...

Setting up Quill in a Nuxt project (a VUE component)

I'm struggling to remove the toolbar in Quill despite my efforts. This is the HTML snippet I am working with: <template> <quill v-model="content" :config="config"></quill> </template Here's what I have inside the scri ...

In PHP, it is essential to always complete the necessary information in form validation

I've been working on implementing JavaScript form validation, but I seem to be having trouble with testing for empty fields in the form. Whenever I submit a fully filled out form, it keeps asking me to fill in the blank fields. Here is the code I hav ...

Retrieving data from a radgrid with the power of jQuery

Trying to extract the text from the label GetName in a radgrid using jQuery. Need to iterate through each record to check the value of the label. Can anyone provide assistance? Thanks! Below is the code for my radgrid. <telerik:RadGrid ID="Gridview1 ...

Unable to interpret encoded json information

I'm currently developing a basic chat system using PHP and jQuery with Ajax, but I've encountered an issue when trying to display a JSON encoded string through the ajax callback function. Below is the code for the ajax request: $.ajax({ url: ...

React State-Driven Conditional Rendering

When selecting both the "Home Team" and "Away Team" options from two dropdowns, I need to display data for both teams in charts. You can view the prototype on codepen. Currently, I am only able to show one Line Component with a dataKey. How can I modify ...

The troubleshooting issue with jQuery animate Scrolltop malfunctioning

My goal is to use jQuery to scroll the page to a specific div when a button is clicked. Despite not seeing any errors in the JavaScript console, the page does not actually scroll to the desired location. I have tried placing the jQuery js file before and a ...

Error: HTML code being displayed instead of form value in Ajax request output

For the past couple of days, I've been struggling with an Ajax issue that I just can't seem to figure out. Despite looking for a solution online, nothing seems to work. Below is the code snippet that's causing me trouble: <!DOCTYPE html& ...

"Exploring the features of next-auth server-side implementation in the latest version of Next.js,

Is it possible to utilize next-auth in a Next.js 14 application router to access user sessions and display page responses using SSR? If so, what steps need to be taken? ...

Creating Objects on the Fly with Mistic Query Builder

As someone who is relatively new to JavaScript, I have mainly focused on Java and PHP development. The JavaScript applications I have built in the past have been somewhat messy, difficult to test, and not easily extendable. Currently, I am working on crea ...

Obtain the date in ISO format without subtracting the timezone offset

I need to obtain a Date string without the timezone being added or subtracted. Currently, when I set my OS timezone to GMT +13 and create a new Date() object, the toISOString() method subtracts one day. For example, today is 11/02. If I adjust my OS time ...

Understanding the envMap and MeshPhong Material within three.js

My attempt to incorporate an environmental map into my PhongMaterial resulted in my geometry disappearing. Take a look at the code snippet below: var reflection = THREE.ImageUtils.loadTextureCube( [ 'textures/hdr/pos-x.png', 'textures/hdr/ ...

AJAX function in Chrome console is throwing an error message stating "Unexpected Token }"

Dealing with this issue has been quite unusual for me. I've spent the last 3 days trying to troubleshoot it, but now it's no longer bothering me. The situation involves a button and a textbox that sends the data from the textbox to a PHP page whe ...

What is the best way to transform a UTC/GMT date and time into CST in Javascript? (CST specifically, not based on

Dealing with a tricky situation where backend data is always stored in UTC time while our front-end data is in CST. Unfortunately, I don't have access to the system handling this 'black box' conversion. Trying to replicate this setup in our ...

JSON input that appears to be correct but unexpectedly ends

I'm currently coding a discord bot and came across this snippet: function addFunds(id, amount){ accounts = fs.readFileSync("accounts.data", 'utf8'); console.log(JSON.parse(accounts)) var obj = JSON.parse(accounts); var i; for (i in ...