Animations with alpha textures in Three.js
Create seemingly complex animations with a few lines of code
Continuing my exploration of mr.doob’s experiments (first part here) here’s one other cool trick I’ve learned and I’d like to share: animations with alpha textures.
Here’s the original scene. The animation of the main sphere is what we will achieve. It’s actually pretty straight forward to implement, it basically is an alpha texture translated at each frame.
Let’s start by creating our material.
It’s important to set transparent to true, otherwise the alpha texture is useless.
Also we need to see the internal surface of our geometry, besides the external one. Therefore we have to enable double side rendering.
I’m not entirely sure why we have to increase the alphaTest value (default is 0). Maybe the internal surface has a weird opacity value.
var material = new THREE.MeshStandardMaterial({ color: "#000", transparent: true, side: THREE.DoubleSide, alphaTest: 0.5 });
Now we’re going to load an image and use it as an alpha texture on our material. Here’s the image we’re going to use:
var alphaMap = new THREE.TextureLoader().load('alpha.png');
material.alphaMap = alphaMap;
material.alphaMap.magFilter = THREE.NearestFilter;
material.alphaMap.wrapT = THREE.RepeatWrapping;
material.alphaMap.repeat.y = 1;
Nice! if we apply our material to a simple sphere this is how it looks like:
It’s not moving yet, but we’re almost there.
In order animate the sphere, we only need to offset the coordinates of the texture in the render loop.
In your update function, the one called every frame (where you call renderer.render(scene, camera)), add this line of code:
mesh.material.alphaMap.offset.y = time*0.002;
here “time” is the elapsed time from the start of the scene.
Here we go. Here’s our animated sphere. So cool and yet so easy :)
Obviously by using different textures is possible to obtain different effects.
Complete example:
var geometry = new THREE.IcosahedronGeometry(30, 5);
var material = new THREE.MeshStandardMaterial({ color: “#444”, transparent: true, side: THREE.DoubleSide, alphaTest: 0.5 });
var alphaMap = new THREE.TextureLoader().load('alpha.png');
material.alphaMap = alphaMap;
material.alphaMap.magFilter = THREE.NearestFilter;
material.alphaMap.wrapT = THREE.RepeatWrapping;
material.alphaMap.repeat.y = 1;var mesh = new THREE.Mesh(geometry, material);scene.add(mesh);// execute this code every frame
mesh.material.alphaMap.offset.y = time*0.0015;
Here’s a codepen for you to play around with (the textures are loaded as data uri, to avoid references external to the codepen).
Where can you find me?
Follow me on Twitter: https://twitter.com/psoffritti
My website/portfolio: pierfrancescosoffritti.com
My GitHub account: https://github.com/PierfrancescoSoffritti
My LinkedIn account: linkedin.com/in/pierfrancescosoffritti/en