three.js - How can I dynamically change object's opacity?
THREE.MeshLambertMaterial
extends THREE.Material
which means it inherits the opacity
property, so all you need to do is access the material on your object, and change the opacity of the material:
object.materials[0].opacity = 1 + Math.sin(new Date().getTime() * .0025);//or any other value you like
Also note that the material must have it's transparent
property set to true.
object.materials[0].transparent = true;
(Thank you Drew and Dois for pointing this out)
Update
the property is now simply material
:
// enable transparency
object.material.transparent = true;
// set opacity to 50%
object.material.opacity = 0.5;
var map = THREE.ImageUtils.loadTexture( myJSONObject[i].url );
var material = new THREE.MeshLambertMaterial( { map: map, transparent: true } );
var object = new THREE.Mesh( geometry, material );
material.opacity = 0.6;
I know this question is very old but I wanted to give my answer from what I used in case someone needs it. With three.js, I used tweening through Greensock's TweenMax/TweenLite. With that, I was able to tween any property of any object and it ran smoothly. Check out the library here. All I needed to tween the properties was:
TweenLite.to(object, duration, properties);
where duration is in seconds and properties are in an object. The "gotcha" for this, especially while using three.js, is to make sure you get specific with the object parameter. For example, per this question, if you are changing the opacity of a mesh, you cannot do
TweenLite.to(mesh, 2, {material.opacity: 0});
rather, you need to be more specific and write
TweenLite.to(mesh.material, 2, {opacity: 0});
I hope this helps someone. Tweening is really awesome!