BorisD
BorisD

Reputation: 2261

three.js - How can I dynamically change object's opacity?

This is my object:

var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { map: THREE.ImageUtils.loadTexture( "image.png" ) } ) );
object.position.set(2, 3, 1.5);

now after I've created this object in init(); function, I can directly go to the object and change his position,like this:

object.position.x = 15;

Now the question is how can I change the opacity of the texture???

Thanks :-)

Upvotes: 52

Views: 76460

Answers (3)

George Profenza
George Profenza

Reputation: 51837

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; 

Upvotes: 85

Martavis P.
Martavis P.

Reputation: 1838

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!

Upvotes: 9

BorisD
BorisD

Reputation: 2261

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;

Upvotes: 13

Related Questions