You can create a lot of interesting visualizations using the various materials available with Three.js. In this recipe, we'll look at how you can use the materials available with Three.js to make part of an object transparent. This will allow you to create complex-looking geometries with relative ease.
Before we dive into the required steps in Three.js, we first need to have the texture that we will use to make an object partially transparent. For this recipe, we will use the following texture, which was created in Photoshop:
You don't have to use Photoshop; the only thing you need to keep in mind is that you use an image with a transparent background. Using this texture, in this recipe, we'll show you how you can create the following (04.08-make-part-of-object-transparent.html
):
As you can see in the preceeding, only part of the sphere is visible, and you can look through the sphere to see the back at the other side of the sphere.
Let's look at the steps you need to take to accomplish this:
THREE.SphereGeometry
:var sphereGeometry = new THREE.SphereGeometry(6, 20, 20);
Just like all the other recipes, you can use whatever geometry you want.
var mat = new THREE.MeshPhongMaterial(); mat.map = new THREE.ImageUtils.loadTexture( "../assets/textures/partial-transparency.png"); mat.transparent = true; mat.side = THREE.DoubleSide; mat.depthWrite = false; mat.color = new THREE.Color(0xff0000);
As you can see in this fragment, we create THREE.MeshPhongMaterial
and load the texture we saw in the Getting ready section of this recipe. To render this correctly, we also need to set the side property to THREE.DoubleSide
so that the inside of the sphere is also rendered, and we need to set the depthWrite
property to false. This will tell WebGL that we still want to test our vertices against the WebGL depth buffer, but we don't write to it. Often, you need to set this to false when working with more complex transparent objects or particles.
var sphere = new THREE.Mesh(sphereGeometry, mat); scene.add(sphere);
With these simple steps, you can create really interesting effects by just experimenting with textures and geometries.
With Three.js, it is possible to repeat textures (refer to the Setup repeating textures recipe). You can use this to create interesting-looking objects such as this:
The code required to set a texture to repeat is the following:
var mat = new THREE.MeshPhongMaterial(); mat.map = new THREE.ImageUtils.loadTexture( "../assets/textures/partial-transparency.png"); mat.transparent = true; mat.map.wrapS = mat.map.wrapT = THREE.RepeatWrapping; mat.map.repeat.set( 4, 4 ); mat.depthWrite = false; mat.color = new THREE.Color(0x00ff00);
By changing the mat.map.repeat.set
values, you define how often the texture is repeated.
18.227.161.225