Skip to content
ImagineWorld

Loading and Working with Textures

node_idnode-book_learn-three-js_chapter-10-loading-and-working-with-textures
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleLoading and Working with Textures
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — Loading and Working with Textures

Section titled “Chapter 10 — Loading and Working with Textures”

In Chapter 4, Working with Three.js Materials, we introduced you to the various materials that are available in Three.js. However, we didn’t discuss applying textures to the material that’s used when creating a mesh. In this chapter, we’ll look at that subject. Specifically, we’ll discuss the following topics:

  • Loading textures in Three.js and applying them to a mesh
  • Using bump, normal, and displacement maps to apply depth and detail to a mesh
  • Creating fake shadows using a lightmap and an ambient occlusion map
  • Using specular, metalness, and roughness maps to set the shininess of specific parts of a mesh
  • Applying an alpha map for partial transparency of an object
  • Adding detailed reflections to a material using an environment map
  • Using the HTML5 Canvas and video element as input for a texture

Let’s start with a basic example, where we will show you how to load and apply a texture.

There are different ways that textures can be used in Three.js. You can use them to define the colors of the mesh, but you can also use them to define shininess, bumps, and reflections. The first example we will look at, though, is very basic, wherein we will use a texture to define the colors of the individual pixels of a mesh. This is often called a color map or a diffuse map.

Loading a texture and applying it to a mesh

Section titled “Loading a texture and applying it to a mesh”

The most basic usage of a texture is when it’s set as a map on a material. When you use this material to create a mesh, the mesh will be colored based on the supplied texture. Loading a texture and using it on a mesh can be done in the following manner:

const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load
('/assets/textures/ground/ground_0036_color_1k.jpg')

In this code sample, we are using an instance of THREE.TextureLoader to load an image file from a specific location. Using this loader, you can use PNG, GIF, or JPEG images as input for a texture (later in this chapter, we’ll show you how to load other texture formats). Note that textures are loaded asynchronously: if it is a large texture and you render the scene before the texture is completely loaded, you’ll see your meshes without a texture applied for a short time. If you want to wait until a texture has been loaded, you can provide a callback to the textureLoader.load() function:

Const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load
('/assets/textures/ground/ground_0036_color_1k.jpg',
onLoadFunction,
onProgressFunction,
onErrorFunction)

As you can see, the load function takes three additional functions as parameters: onLoadFunction is called when the texture is loaded, onProgressFunction can be used to track how much of the texture is loaded, and onErrorFunction is called when something goes wrong while loading or parsing the texture. Now that the texture has been loaded, we can add it to the mesh:

const material = new THREE.MeshPhongMaterial({ color:
0xffffff })
material.map = texture

Note that the loader also provides a loadAsync function, which returns a Promise instead, just like we saw in the previous chapter when loading models.

You can use pretty much any image you’d like as a texture. However, you’ll get the best results by using a square texture whose dimensions are a power of 2. So, dimensions such as 256 x 256, 512 x 512, 1,024 x 1,024, and so on work the best. If the texture isn’t a power of two, Three.js will scale down the image to the closest power of 2 value.

One of the textures we’ll be using in the examples in this chapter looks like this:

Figure 10.1 – The color texture of a brick wall

The pixels of a texture (also called texels) usually don’t map one-to-one on the pixels of the face. If the camera is very close, we need to magnify the texture, and if we’re zoomed out, we probably need to shrink the texture. For this purpose, WebGL and Three.js offer a couple of different options to resize this image. This is done through the magFilter and minFilter properties:

  • THREE.NearestFilter: This filter uses the color of the nearest texel that it can find. When used for magnification, this will result in blockiness, and when used for minification, the result will lose a lot of detail.
  • THREE.LinearFilter: This filter is more advanced; it uses the color values of the four neighboring texels to determine the correct color. You’ll still lose a lot of detail in minification, but the magnification will be much smoother and less blocky.

Aside from these basic values, we can also use a MIP map. A MIP map is a set of texture images, each half the size of the previous one. These are created when you load the texture and allow for much smoother filtering. So, when you have a square texture (as a power of 2), you can use a couple of additional approaches for better filtering. The properties can be set using the following values:

  • THREE.NearestMipMapNearestFilter: This property selects the MIP map that best maps the required resolution and applies the nearest filter principle, which we discussed in the previous list. Magnification is still blocky, but minification looks much better.
  • THREE.NearestMipMapLinearFilter: This property selects not just a single MIP map but the two nearest MIP map levels. On both of these levels, the nearest filter is applied, to get two intermediate results. These two results are passed through a linear filter to get the final result.
  • THREE.LinearMipMapNearestFilter: This property selects the MIP map that best maps the required resolution and applies the linear filter principle, which was discussed in the previous list.
  • THREE.LinearMipMapLinearFilter: This property selects not a single MIP map, but the two nearest MIP map levels. On both of these levels, a linear filter is applied, to get two intermediate results. These two results are passed through a linear filter to get the final result.

If you don’t specify the magFilter and minFilter properties explicitly, Three.js uses THREE.LinearFilter as the default for the magFilter property and THREE.LinearMipMapLinearFilter as the default for the minFilter property.

In our examples, we’ll just use the default texture properties. An example of such a basic texture used as a map for a material can be found in texture-basics.html. The following screenshot shows this example:

Figure 10.2 – Model with a simple wood texture

In this example, you can change the models and select a couple of textures from the menu on the right. You can also change the default material properties to see how the material, in combination with a color map, is affected by the different settings.

In this example, you can see that the textures wrap nicely around the shapes. When you create geometries in Three.js, it makes sure that any texture that is used is applied correctly. This is done through something called UV mapping. With UV mapping, we can tell the renderer which part of a texture should be applied to a specific face. We’ll get into the details of UV mapping in Chapter 13, Working with Blender and Three.js, where we will show you how you can easily use Blender to create custom UV mappings for Three.js.

Aside from the standard image formats that we can load with THREE.TextureLoader, Three.js also provides a couple of custom loaders you can use to load textures provided in different formats. If you’ve got a specific image format, you can check out the loaders folder from the Three.js distribution (https://github.com/mrdoob/three.js/tree/dev/examples/jsm/loaders) to see whether the image format can be loaded directly by Three.js or whether you need to manually convert it.

Aside from these normal images, Three.js also supports HDR images.

An HDR image captures a higher range of luminance levels than standard images, and can more closely match what we see with the human eye. Three.js supports the EXR and RGBE formats. If you’ve got an HDR image, you can fine-tune how Three.js renders the HDR image since an HDR image contains more luminance information than can be shown on a display. This can be done by setting the following properties in THREE.WebGLRenderer:

  • toneMapping: This property defines how to map the colors from the HDR image to the display. Three.js provides the following options: THREE.NoToneMapping, THREE.LinearToneMapping, THREE.ReinhardToneMapping, THREE.Uncharted2ToneMapping, and THREE.CineonToneMapping. The default is THREE.LinearToneMapping.
  • toneMappingExposure: This is the exposure level of toneMapping. This can be used to fine-tune the colors of the rendered texture.
  • toneMappingWhitePoint: This is the white point used for toneMapping. This can also be used to fine-tune the colors of the rendered texture.

If you want to load an EXR or RGBE image and use it as a texture, you can use THREE.EXRLoader or THREE.RGBELoader. This works in the same way as we’ve seen for THREE.TextureLoader:

const loader = new THREE.EXRLoader();
exrTextureLoader.load('/assets/textures/exr/Rec709.exr')
...
const hdrTextureLoader = new THREE.RGBELoader();
hdrTextureLoader.load('/assets/textures/hdr/
dani_cathedral_oBBC.hdr')

In the texture-basics.html example, we showed you how the texture can be used to apply colors to a mesh. In the next section, we’ll look at how to use a texture to make a model look more detailed by applying fake height information to the mesh.

Using a bump map to provide extra details to a mesh

Section titled “Using a bump map to provide extra details to a mesh”

A bump map is used to add more depth to a material. You can see this in action by opening texture-bump-map.html:

Figure 10.3 – Model with a bump map

In this example, you can see that the model looks much more detailed and seems to have more depth. This was done by setting an additional texture, a so-called bump map, on the material:

const exrLoader = new EXRLoader()
const colorMap = exrLoader.load('/assets/textures/brick-wall/brick_wall_001_diffuse_2k.exr', (texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
})
const bumpMap = new THREE.TextureLoader().load(
'/assets/textures/brick-wall/brick_wall_001_displacement_2k.png',
(texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
}
)
const material = new THREE.MeshPhongMaterial({ color:
0xffffff })
material.map = colorMap
material.bumpMap = bumpMap

In this code, you can see that aside from setting the map property, we have also set the bumpMap property to a texture. Additionally, with the bumpScale property, which is available through the menu in the previous example, we can set the height (or depth, if set to a negative value) of the bumps. The textures used in this example are shown here:

Figure 10.4 – Textures used for the bump map

The bump map is a grayscale image, but you can also use a color image. The intensity of the pixels defines the height of the bump. A bump map only contains the relative height of a pixel. It doesn’t say anything about the direction of the slope. So, the level of detail and perception of depth that you can reach with a bump map is limited. For more detail, you can use a normal map.

Achieving more detailed bumps and wrinkles with a normal map

Section titled “Achieving more detailed bumps and wrinkles with a normal map”

In a normal map, the height (displacement) is not stored, but the direction of the normal for each pixel is stored. Without going into too much detail, with normal maps, you can create very detailed-looking models that use only a small number of vertices and faces. For instance, take a look at the texture-normal-map.html example:

Figure 10.5 – A model using a normal map

In the preceding screenshot, you can see a very detailed-looking model. And as the model moves around, you can see that the texture is responding to the light it receives. This provides a very realistic-looking model and only requires a very simple model and a couple of textures. The following code fragment shows how to use a normal map in Three.js:

const colorMap = new THREE.TextureLoader().load('/assets/textures/red-bricks/red_bricks_04_diff_1k.jpg', (texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
})
const normalMap = new THREE.TextureLoader().load(
'/assets/textures/red-bricks/red_bricks_04_nor_gl_1k.jpg',
(texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
}
)
const material = new THREE.MeshPhongMaterial({ color:
0xffffff })
material.map = colorMap
material.normalMap = normalMap

This involves the same approach as the one we used for the bump map. This time, though, we set the normalMap property to the normal texture. We can also define how pronounced the bumps look by setting the normalScale property (mat.normalScale.set(1,1)). With this property, you can scale along the X and Y axes. The best approach, though, is to keep these values the same. In this example, you can play around with these values.

The following figure shows what the normal map we used here looks like:

Figure 10.6 – Normal texture

The problem with normal maps, however, is that they aren’t very easy to create. You need to use specialized tools, such as Blender or Photoshop. These programs can use high-resolution renderings or textures as input and can create normal maps from them.

With a normal or bump map, you don’t change the shape of the model; all of the vertices stay in the same location. These maps just use the lights from the scene to create fake depth and details. However, Three.js provides a third method that you can use to add details to a model using a map, which does change the positions of the vertices. This is done through a displacement map.

Using a displacement map to alter the position of vertices

Section titled “Using a displacement map to alter the position of vertices”

Three.js also provides a texture that you can use to change the positions of the vertices of your model. While the bump map and the normal map give an illusion of depth, with a displacement map, we change the model’s shape, based on the information from the texture. We can use a displacement map in the same way as we use other maps:

const colorMap = new THREE.TextureLoader().load('/assets/textures/displacement
/w_c.jpg', (texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
})
const displacementMap = new THREE.TextureLoader().load('/assets/textures/displacement
/w_d.png', (texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
})
const material = new THREE.MeshPhongMaterial({ color:
0xffffff })
material.map = colorMap
material.displacementMap = displacementMap

In the preceding code fragment, we loaded a displacement map, which looks as follows:

Figure 10.7 – Displacement map

The brighter the color, the more a vertex is displaced. When you run the texture-displacement.html example, you will see that the result of the displacement map is a model where the shape of the model is changed based on the information from the map:

Figure 10.8 – Model using a displacement map

Aside from setting the displacementMap texture, we can also use displacementScale and displacementOffset to control how pronounced the displacement is. One final thing to mention about using a displacement map is that it will only have good results if your mesh contains a large number of vertices. If not, the displacement won’t look like the provided texture, since there are too few vertices to represent the required displacement.

Adding subtle shadows with an ambient occlusion map

Section titled “Adding subtle shadows with an ambient occlusion map”

In the previous chapters, you learned how you can use shadows in Three.js. If you set the castShadow and receiveShadow properties of the correct meshes, add a couple of lights, and configure the shadow camera of the lights correctly, Three.js will render shadows.

Rendering shadows, however, is a rather expensive operation that is repeated for every render loop. If you have lights or objects that are moving around, this is necessary, but often, some of the lights or models are fixed, so it would be great if we could calculate the shadows once, and then reuse them. To accomplish this, Three.js offers two different maps: the ambient occlusion map and a lightmap. In this section, we’ll look at the ambient occlusion map, and in the next section, we’ll look at the lightmap.

Ambient occlusion is a technique used to determine how much each part of a model is exposed to the ambient lighting in a scene. In tools such as Blender, ambient light is often modeled through a hemisphere light or a directional light, such as the Sun. While most parts of a model will receive some of this ambient lighting, not all of the parts will receive the same. If, for instance, you model a person, the top of the head will receive more ambient lighting than the bottom of the arms. This difference in lighting – the shadows – can be rendered (baked, as shown in the following screenshot) into a texture, and we can then apply that texture to our models to give them shadows, without having to calculate the shadows every time:

Figure 10.9 – Ambient occlusion map baked in Blender

Once you have an ambient occlusion map, you can assign it to the aoMap property of the material, and Three.js will take this information into account when applying and calculating how much the lights in the scene should be applied to that specific part of the model. The following code fragment shows how to set the aoMap property:

const aoMap = new THREE.TextureLoader().load('/assets/gltf/material_
ball_in_3d-coat/aoMap.png')
const material = new THREE.MeshPhongMaterial({ color:
0xffffff })
material.aoMap = aoMap
material.aoMap.flipY = false

Just like the other kinds of texture maps, we just use THREE.TextureLoader to load the texture and assign it to the correct property of the material. And like with many of the other maps, we can also tune how much the map affects the lighting of the model by setting the aoMapIntenisty property. In this example, you can also see that we needed to set the flipY property of aoMap to false. Sometimes, external programs store the material in a texture slightly different than Three.js expects. With this property, we flip the orientation of the texture. This is usually something you’ll notice by trial and error when working with the model.

To make an ambient occlusion map work, we will (usually) need one additional step. We have already mentioned UV mappings (stored in the uv attribute). These define which part of a texture is mapped to a specific face of the model. For the ambient occlusion map, and also for the lightmap in the following example, Three.js uses a separate set of UV mappings (stored in the uv2 attribute) because, often, the other textures need to be applied differently than the shadow and lightmap textures. For our example, we are just copying the UV mappings from the model; remember that when we use the aoMap property or the lightMap property, Three.js will use the value of the uv2 attribute, instead of the uv attribute. If this attribute isn’t present in the model you load, most often, just copying the uv map property works as well since we didn’t do anything to optimize the ambient occlusion map, which might require a different set of UVs:

const k = mesh.geometry
const uv1 = k.getAttribute('uv')
const uv2 = uv1.clone()
k.setAttribute('uv2', uv2)

We will provide two examples where we use an ambient occlusion map. In the first one, we are showing the model from Figure 10*.9* with aoMap applied (texture-ao-map-model.html):

Figure 10.10 – Ambient occlusion map baked in Blender and then applied to a model

You can use the menu on the right to set aoMapIntensity. The higher this value is, the more shadows you’ll see from the loaded aoMap texture. As you can see, it is really useful to have an ambient occlusion map as it provides great details for the model, and makes it look much more lifelike. Some of the textures we’ve seen in this chapter already also provide an additional aoMap that you can use. If you open texture-ao-map.html, you will get a simple brick-like texture, but this time with aoMap added as well:

Figure 10.11 – Ambient occlusion map combined with color and normal maps

While an ambient occlusion map changes the amount of light received by certain parts of the model, Three.js also supports lightmap, which do the opposite (approximately) by specifying a map that adds extra lighting to certain parts of the model.

In this section, we’ll use a lightmap. A lightmap is a texture that contains information about how much the lights in the scene will affect the model. In other words, the effect of the lights is baked into a texture. Lightmaps are baked in 3D software, such as Blender, and contain the light values of each part of the model:

Figure 10.12 – Lightmap baked in Blender

The lightmap that we’ll use in this example is shown in Figure 10*.12*. The right part of the edit window shows a baked lightmap for the ground plane. You can see that the whole ground plane is illuminated with white light, and parts of it receive less light because there is also a model in the scene. The code for using a lightmap is similar to that of an ambient occlusion map:

Const textureLoader = new THREE.TextureLoader()
const colorMap = textureLoader.load('/assets/textures/wood/
abstract-antique-backdrop-164005.jpg')
const lightMap = textureLoader.load('/assets/gltf/
material_ball_in_3d-coat/lightMap.png')
const material = new THREE.MeshBasicMaterial({ color:
0xffffff })
material.map = colorMap
material.lightMap = lightMap
material.lightMap.flipY = false

Once again, we need to provide Three.js with an additional set of uv values called uv2 (not shown in the code), and we must use THREE.TextureLoader to load the textures – in this case, a simple texture is used for the colors of the floor and the lightmap created for this example in Blender. The result looks as follows (texture-light-map.html):

Figure 10.13 – Using a lightmap for false shadows

If you look at the preceding example, you will see that the information from the lightmap is used to create a very nice-looking shadow, which seems to be cast by the model. It is important to remember that baking shadows, lights, and ambient occlusion works great in static scenes with static objects. As soon as objects or light sources change or start to move, you will have to calculate the shadows in real time.

When discussing the materials available in Three.js, we mentioned that a good default material to use is THREE.MeshStandardMaterial. You can use this to create shiny, metal-like materials, but also to apply roughness, to make the mesh look more like wood or plastic. By using the metalness and roughness properties of the material, we can configure the material to represent the material that we want. Aside from these two properties, you can also configure these properties by using a texture. So, if we have a rough object and we want to specify that a certain part of that object is shiny, we can set the metalnessMap property of THREE.MeshStandardMaterial, and if we want to indicate that some parts of the mesh should be seen as scratched or rougher, we can set the roughnessMap property. When you use these maps, the value of the texture for a specific part of the model is multiplied by either the roughness property or the metalness property, and that determines how that specific pixel should be rendered. First, we will look at the metalness property in texture-metalness-map.html:

Figure 10.14 – Metalness texture applied to a model

In this example, we’ve skipped ahead a bit and have also used an environment map, which allows us to render reflections from the environment on top of the objects. An object with a high metalness reflects more, and an object with a high roughness diffuses the reflection more. For this model, we’ve used metalnessMap; you can see that the object itself is shiny where the metalness property from the texture is high and that some parts are rough where the metalness property from the texture is low. When looking at roughnessMap, we can see pretty much the same but inverted:

Figure 10.15 – Roughness texture applied to a model

As you can see, based on the provided texture, certain parts of the model are rougher or more scratched than other parts. For metalnessMap, the value of the material is multiplied by the metalness property of the material; for roughnessMap, the same applies, but in that case, the value is multiplied by the roughness property.

Loading these textures and setting them to the material can be done like so:

const metalnessTexture = new THREE.TextureLoader().load(
'/assets/textures/engraved/Engraved_Metal_003_ROUGH.jpg',
(texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
}
)
const material = new THREE.MeshStandardMaterial({ color:
0xffffff })
material.metalnessMap = metalnessTexture
...
const roughnessTexture = new THREE.TextureLoader().load(
'/assets/textures/marble/marble_0008_roughness_2k.jpg',
(texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(2, 2)
}
)
const material = new THREE.MeshStandardMaterial({ color:
0xffffff })
material.roughnessMap = roughnessTexture

Next up is the alpha map. With the alpha map, we can use a texture to change the transparency of parts of the model.

Using an alpha map to create transparent models

Section titled “Using an alpha map to create transparent models”

An alpha map is a way to control the opacity of the surface. If the value of the map is black, that part of the model will be fully transparent, and if it is white, it will be fully opaque. Before we look at the texture and how to apply it, we’ll first look at the example (texture-alpha-map.html):

Figure 10.16 – Alpha map used to give partial transparency

In this example, we’ve rendered a cube and set the alphaMap property of the material. If you open this example, make sure to set the transparency property of the material to true. You’ll probably notice that you can only see the front-facing part of the cube, unlike the preceding screenshot, where you can look through the cube and see the other side. The reason is that, by default, the side property of the used material is set to THREE.FrontSide. To render the side that is normally hidden, we have to set the side property of the material to THREE.DoubleSide; you will see that the cube is rendered as shown in the preceding screenshot.

The texture that we used in this example is a very simple one:

Figure 10.17 – Texture used to create a transparent model

To load it, we must use the same approach as that of the other textures:

const alphaMap = new THREE.TextureLoader().load('/assets/
textures/alpha/partial-transparency.png', (texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
})
const material = new THREE.MeshPhongMaterial({ color:
0xffffff })
material.alphaMap = alphaMap
material.transparent = true

In this code fragment, you can also see that we’ve set the wrapS, wrapT, and repeat properties of the texture. We’ll explain these properties in more detail later in this chapter, but these properties can be used to determine how often we want to repeat the texture on the mesh. If set to (1, 1), the whole texture won’t be repeated when applied to the mesh; if set to higher values, the texture will shrink and will be repeated multiple times. In this case, we repeated it in both directions four times.

Using an emissive map for models that glow

Section titled “Using an emissive map for models that glow”

The emissive map is a texture that can be used to make certain parts of the model glow, just like the emissive property does for the whole model. Just as for the emissive property, using an emissive map doesn’t mean this object is emitting light – it just makes the part of the model where this texture is applied seem to glow. This is easier to understand by looking at an example. If you open up the texture-emissive-map.html example in your browser, you will see a lava-like object:

Figure 10.18 – Lava-like object using an emissive map

When you look closely, though, you might see that while the objects seem to glow, the objects themselves don’t emit light. This means that you can use this to enhance objects, but the objects themselves don’t contribute to the lighting of the scene. For this example, we used an emissive map that looks as follows:

Figure 10.19 – Lava texture

To load and use an emissive map, we can use a THREE.TextureLoader to load one and assign it to the emissiveMap property (together with some other maps to get the model shown in Figure 10*.18*):

const emissiveMap = new THREE.TextureLoader().load
('/assets/textures/lava/lava.png', (texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
})
const roughnessMap = new THREE.TextureLoader().load
('/assets/textures/lava/lava-smoothness.png', (texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
})
const normalMap = new THREE.TextureLoader().load
('/assets/textures/lava/lava-normals.png', (texture) => {
texture.wrapS = THREE.RepeatWrapping
texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(4, 4)
})
const material = new THREE.MeshPhongMaterial({ color:
0xffffff })
material.normalMap = normalMap
material.roughnessMap = roughnessMap
material.emissiveMap = emissiveMap
material.emissive = new THREE.Color(0xffffff)
material.color = new THREE.Color(0x000000)

Since the color from emissiveMap is modulated with the emissive property, make sure that you set the emissive property of the material to something other than black.

Using a specular map to determine shininess

Section titled “Using a specular map to determine shininess”

In the previous examples, we mostly used THREE.MeshStandardMaterial, and the different maps supported by that material. THREE.MeshStandardMaterial is often your best choice if you need a material since it can be easily configured to represent a large number of different types of real-world materials. In older versions of Three.js, you had to use THREE.MeshPhongMaterial for shiny materials and THREE.MeshLambertMaterial for non-shiny materials. The specular map used in this section can only be used together with THREE.MeshPhongMaterial. With a specular map, you can define which parts of the model should be shiny, and which parts of them should be rough (similar to metalnessMap and roughnessMap, which we saw earlier). In the texture-specular-map.html example, we’ve rendered the Earth and used a specular map to make the oceans shinier than the landmasses:

Figure 10.20 – Specular map showing reflecting oceans

By using the menu at the top right, you can play around with the specular color and the shininess. As you can see, these two properties affect how the oceans reflect light, but they don’t change the landmasses’ shininess. This is because we’ve used the following specular map:

Figure 10.21 – Specular map texture

In this map, the black color means that those parts of the map have a shininess of 0%, and the white parts have a shininess of 100%.

To use a specular map, we must use THREE.TextureLoader to load the map and assign it to the specularMap property of a THREE.MathPhongMaterial:

const colorMap = new THREE.TextureLoader().load
('/assets/textures/specular/Earth.png')
const specularMap = new THREE.TextureLoader().load
('/assets/textures/specular/EarthSpec.png')
const normalMap = new THREE.TextureLoader().load
('/assets/textures/specular/EarthNormal.png')
const material = new THREE.MeshPhongMaterial({ color:
0xffffff })
material.map = colorMap
material.specularMap = specularMap
material.normalMap = normalMap

With the specular map, we’ve discussed most of the basic textures that you can use to add depth, color, transparency, or additional light effects to your model. In the next two sections, we’ll look at one more type of map, which will allow you to add environment reflections to your model.

Creating fake reflections using an environment map

Section titled “Creating fake reflections using an environment map”

Calculating environment reflections is very CPU-intensive, and it usually requires a ray tracer approach. If you want to use reflections in Three.js, you can still do that, but you’ll have to fake it. You can do so by creating a texture of the environment the object is in and applying it to the specific object. First, we’ll show you the result that we’re aiming for (see texture-environment-map.html, which is shown in the following screenshot):

Figure 10.22 – Environment map showing the inside of a car

In the preceding screenshot, you can see that the sphere reflects the environment. If you move your mouse around, you will also see that the reflection corresponds with the camera angle, concerning the environment you see. To create this example, perform the following steps:

  1. Create a CubeTexture object. A CubeTexture is a set of six textures that can be applied to each side of a cube.
  2. Set the skybox. When we have a CubeTexture, we can set it as the background of the scene. If we do this, we effectively create a very large box, inside of which the cameras and objects are placed, so that when we move the camera around, the background of the scene also changes correctly. Alternatively, we could also create a very large cube, apply CubeTexture, and add it to the scene ourselves.
  3. Set the CubeTexture object as a texture of the cubeMap property of the material. The same CubeTexture object that we used to simulate the environment should be used as a texture on the meshes. Three.js will make sure it looks like a reflection of the environment.

Creating a CubeTexture is pretty easy, once you have the source material. What you will need are six images that, together, make up a complete environment. So, you will need the following pictures:

  • Looking forward (posz)
  • Looking backward (negz)
  • Looking up (posy)
  • Looking down (negy)
  • Looking right (posx)
  • Looking left (negx)

Three.js will patch these together to create a seamless environment map. There are several sites where you can download panoramic images, but they are often in a spherical equirectangular format, which looks as follows:

Figure 10.23 – Equirectangular format cube map

There are two ways you can use these kinds of maps. First, you can convert it into a cube map format consisting of six separate files. You can convert this online using the following site: https://jaxry.github.io/panorama-to-cubemap/.

Alternatively, you can use a different way to load this texture into Three.js, which we’ll show later in this section.

To load a CubeTexture from six separate files, we can use THREE.CubeTextureLoader, like this:

const cubeMapFlowers = new THREE.CubeTextureLoader().load([
'/assets/textures/cubemap/flowers/right.png',
'/assets/textures/cubemap/flowers/left.png',
'/assets/textures/cubemap/flowers/top.png',
'/assets/textures/cubemap/flowers/bottom.png',
'/assets/textures/cubemap/flowers/front.png',
'/assets/textures/cubemap/flowers/back.png'
])
const material = new THREE.MeshPhongMaterial({ color:
0x777777 }
material.envMap = cubeMapFlowers
material.mapping = THREE.CubeReflectionMapping

Here, you can see that we’ve loaded a cubeMap out of several different images. Once loaded, we assign the texture to the envMap property of a material. Finally, we must inform Three.js of which kind of mapping we want to use. If you load a texture using THREE.CubeTextureLoader, you can use THREE.CubeReflectionMapping or THREE.CubeRefractionMapping. The first one will make your object show reflections based on the loaded cubeMap, while the second one will turn your model into a more translucent glass-like object that refracts the lights slightly, once again based on the information from cubeMap.

We can also set this cubeMap as a background for the scene, like this:

scene.background = cubeMapFlowers

When you’ve got a single image, the process isn’t much different:

const cubeMapEqui = new THREE.TextureLoader().load
('/assets/equi.jpeg')
const material = new THREE.MeshPhongMaterial({ color:
0x777777 }
material.envMap = cubeMapEqui
material.mapping = THREE.EquirectangularReflectionMapping
scene.background = cubeMapFlowers

This time, we used the normal texture loader, but by specifying a different mapping, we can inform Three.js how to render this texture. When using this approach, you can set the mapping to either THREE.EquirectangularRefractionMapping or THREE.EquirectangularReflectionMapping.

The result of both these approaches is a scene where it looks like we’re standing in a wide, outdoor environment, where the meshes reflect the environment. The menu on the side allows you to set the properties of the material:

Figure 10.24 – Using refraction to create glass-like objects

Aside from reflection, Three.js also allows you to use a cubeMap object for refraction (glass-like objects). The following screenshot shows this (you can test this yourself by using the menu on the right):

Figure 10.25 – Using refraction to create glass-like objects

To get this effect, we only need to set the mapping property of cubeMap to THREE.CubeRefractionMapping (the default is the reflection, which can also be set manually by specifying THREE.CubeReflectionMapping):

cubeMap.mapping = THREE.CubeRefractionMapping

In this example, we used a static environment map for the meshes. In other words, we only saw the environment’s reflection and not the other meshes in the environment. In the following screenshot, you can see that, with a little bit of work, we can show the reflections of other objects as well:

Figure 10.26 – Using a cubeCamera to create dynamic reflections

To also show reflections from the other objects in the scene, we need to use some other Three.js components. The first of them is an additional camera called THREE.CubeCamera:

const cubeRenderTarget = new THREE.WebGLCubeRenderTarget
(128, {
generateMipmaps: true,
minFilter: THREE.LinearMipmapLinearFilter
})
const cubeCamera = new THREE.CubeCamera(0.1, 10, cubeRenderTarget)
cubeCamera.position.copy(mesh.position);
scene.add(cubeCamera);

We will use THREE.CubeCamera to take a snapshot of the scene with all of the objects rendered and use that to set up a cubeMap. The first two arguments define the near and far properties of the camera. So, in this case, the camera only renders what it can see from 0.1 to 1.0. The last property is the target to which we want to render the texture. For that, we’ve created an instance of a THREE.WebGLCubeRenderTarget. The first parameter is the size of the render target. The higher the value, the more detailed the reflection will look. The other two properties are used to determine how the texture is scaled up and down when you zoom in.

You need to make sure that you position this camera at the exact location of THREE.Mesh on which you want to show the dynamic reflections. In this example, we copied the position from the mesh so that the camera is positioned correctly.

Now that we have CubeCamera set up correctly, we need to make sure that what CubeCamera sees is applied as a texture to the cube in our example. To do this, we must set the envMap property to cubeCamera.renderTarget:

cubeMaterial.envMap = cubeRenderTarget.texture;

Now, we have to make sure that cubeCamera renders the scene so that we can use that output as input for the cube. For this, we must update the render loop as follows (or if the scene doesn’t change, we can just call this once):

const render = () => {
...
mesh.visible = false;
cubeCamera.update(renderer, scene);
mesh.visible = true;
requestAnimationFrame(render);
renderer.render(scene, camera);
....
}

As you can see, first, we disable the visibility of mesh. We do this because we only want to see reflections from the other objects. Next, we render the scene using cubeCamera by calling the update function. After that, we make mesh visible again and render the scene as normal. The result is that, in the reflection of mesh, you can see the cubes that we added. For this example, every time you click on the updateCubeCamera button, the envMap property of the mesh will be updated.

When you apply a texture to a geometry created by Three.js, Three.js will try to apply the texture as optimally as possible. For instance, for cubes, this means that each side will show the complete texture, and for spheres, the complete texture is wrapped around the sphere. However, there are situations where you won’t want the texture to spread around a complete face or the complete geometry, but rather have the texture repeat itself. Three.js provides functionality that allows you to control this. An example where you can play around with the repeat properties is provided in texture-repeat-mapping.html. The following screenshot shows this example:

Figure 10.27 – Repeat wrapping on a sphere

Before this property has the desired effect, you need to make sure that you set the wrapping of the texture to THREE.RepeatWrapping, as shown in the following code snippet:

mesh.material.map.wrapS = THREE.RepeatWrapping;
mesh.material.map.wrapT = THREE.RepeatWrapping;

The wrapS property defines how you want the texture to wrap along its X -axis, and the wrapT property defines how the texture should be wrapped along its Y -axis. Three.js provides three options for this, which are as follows:

  • THREE.RepeatWrapping allows the texture to repeat itself
  • THREE.MirroredRepeatWrapping allows the texture to repeat itself, but each repetition is mirrored
  • THREE.ClampToEdgeWrapping is a default setting where the texture doesn’t repeat as a whole; only the pixels at the edge are repeated

In this example, you can play around with the various repeat settings and wrapS and wrapT options. Once the wrapping type has been selected, we can set the repeat property, as shown in the following code fragment:

mesh.material.map.repeat.set(repeatX, repeatY);

The repeatX variable defines how often the texture is repeated along its X -axis, and the repeatY variable defines the same for the Y -axis. If these values are set to 1, the texture won’t repeat itself; if they are set to a higher value, you’ll see that the texture will start to repeat. You can also use values lower than 1. In that case, you’ll zoom in on the texture. If you set the repeat value to a negative value, the texture will be mirrored.

When you change the repeat property, Three.js will automatically update the textures and render them with this new setting. If you change from THREE.RepeatWrapping to THREE.ClampToEdgeWrapping, you will have to explicitly update the texture using mesh.material.map.needsUpdate = true;:

Figure 10.28 – Clamp to edge wrapping on a sphere

So far, we’ve only used static images for our textures. However, Three.js also has the option to use the HTML5 canvas as a texture.

Rendering to a canvas and using it as a texture

Section titled “Rendering to a canvas and using it as a texture”

In this section, we will look at two different examples. First, we will look at how you can use the canvas to create a simple texture and apply it to a mesh; after that, we’ll go one step further and create a canvas that can be used as a bump map, using a randomly generated pattern.

In this first example, we’ll render a fractal to an HTML Canvas element and use that as a color map for our mesh. The following screenshot shows this example (texture-canvas-as-color-map.html):

Figure 10.29 – Using an HTML canvas as a texture

First, we’ll look at the code required to render the fractal:

import Mandelbrot from 'mandelbrot-canvas'
...
const div = document.createElement('div')
div.id = 'mandelbrot'
div.style = 'position: absolute'
document.body.append(div)
const mandelbrot = new Mandelbrot(document.getElementById('mandelbrot'), {
height: 300,
width: 300,
magnification: 100
})
mandelbrot.render()

We won’t go into too much detail, but this library requires a div element as input and will create a canvas element inside that div. The preceding code will render the fractal, as you can see in the previous screenshot. Next, we need to assign this canvas to the map property of our material:

const material = new THREE.MeshPhongMaterial({
color: 0xffffff,
map: new THREE.Texture(document.querySelector
('#mandelbrot canvas'))
})
material.map.needsUpdate = true

Here, we just create a new THREE.Texture and pass in the reference to the canvas element. The only thing we need to do is set material.map.needsUpdate to true, which will trigger Three.js to get the latest information from the canvas element, at which point we will see it applied to the mesh.

We can, of course, use this same idea for all of the different types of maps that we’ve seen so far. In the next example, we’ll use the canvas as a bump map.

As you saw earlier in this chapter, we can add height to our model using a bump map. The higher the intensity of a pixel in this map, the higher the wrinkling. Since a bump map is just a simple black-and-white image, nothing keeps us from creating it on a canvas and using that canvas as an input for the bump map.

In the following example, we will use a canvas to generate a Perlin noise-based grayscale image, and we will use that image as input for the bump map that we apply to the cube. See the texture-canvas-as-bump-map.html example. The following screenshot shows this example:

Figure 10.30 – Using an HTML canvas as a bump map

The approach for this is pretty much the same as we saw in the previous canvas example. We need to create a canvas element and fill that canvas with some noise. To do so, we must use Perlin noise. Perlin noise generates a very natural-looking texture, as you can see in the preceding screenshot. More information on Perlin noise and other noise generators can be found here: https://thebookofshaders.com/11/. The code to accomplish this is shown here:

import generator from 'perlin'
var canvas = document.createElement('canvas')
canvas.className = 'myClass'
const size = 512
canvas.style = 'position:absolute;'
canvas.width = size
canvas.height = size
document.body.append(canvas)
const ctx = canvas.getContext('2d')
for (var x = 0; x < size; x++) {
for (var y = 0; y < size; y++) {
var base = new THREE.Color(0xffffff)
var value = (generator.noise.perlin2(x / 8, y / 8) + 1) / 2
base.multiplyScalar(value)
ctx.fillStyle = '#' + base.getHexString()
ctx.fillRect(x, y, 1, 1)
}
}

We use the generator.noise.perlin2 function to create a value from 0 to 1, based on the x and y coordinates of the canvas element. This value is used to draw a single pixel on the canvas element. Doing this for all the pixels creates the random map that you can see in the top-left corner of the preceding screenshot. This map can then be used as a bump map:

const material = new THREE.MeshPhongMaterial({
color: 0xffffff,
bumpMap: new THREE.Texture(canvas)
})
material.bumpMap.needsUpdate = true

Using a THREE.DataTexture for a dynamic texture

In this example, we rendered Perlin noise using an HTML canvas element. Three.js also provides an alternative way to dynamically create a texture: you can create a THREE.DataTexture texture, where you can pass in a Uint8Array where you can directly set the RGB values. More information on how to use a THREE.DataTexture can be found here: https://threejs.org/docs/#api/en/textures/DataTexture.

The final input that we use for the texture is another HTML element: the HTML5 video element.

Using the output from a video as a texture

Section titled “Using the output from a video as a texture”

If you read the preceding section on rendering to a canvas, you may have thought about rendering video to a canvas and using that as input for a texture. That’s one way to do it, but Three.js already has direct support to use the HTML5 video element (through WebGL). Check out texture-canvas-as-video-map.html:

Figure 10.31 – Using an HTML video as a texture

Using video as input for a texture is easy, just like using the canvas element. First, we need a video element to play the video:

const videoString = \`
<video
id="video"
src="/assets/movies/Big_Buck_Bunny_small.ogv"
controls="true"
</video>
\`
const div = document.createElement('div')
div.style = 'position: absolute'
document.body.append(div)
div.innerHTML = videoString

This creates a basic HTML5 video element, by setting the HTML string directly to the innerHTML property of the div element. While this works great for testing, frameworks and libraries usually provide better options for this. Next, we can configure Three.js to use the video as an input for a texture, as follows:

const video = document.getElementById('video')
const texture = new THREE.VideoTexture(video)
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
map: texture
})

The result can be seen in the texture-canvas-as-video-map.html example.

With that, we have completed this chapter on textures. As you’ve seen, a lot of textures are available in Three.js, each with a different use. You can use any image in PNG, JPG, GIF, TGA, DDS, PVR, TGA, KTX, EXR, or RGBE format as a texture. Loading these images is done asynchronously, so remember to either use a rendering loop or add a callback when you load a texture. With the different types of textures available, you can create great-looking objects from low-poly models.

With Three.js, it is also easy to create dynamic textures, using either the HTML5 canvas element or the video element – just define a texture with these elements as the input, and set the needsUpdate property to true whenever you want the texture to be updated.

With this chapter out of the way, we’ve pretty much covered all of the important concepts of Three.js. However, we haven’t looked at an interesting feature that Three.js offers: postprocessing. With postprocessing, you can add effects to your scene after it has been rendered. You can, for instance, blur or colorize your scene, or add a TV-like effect using scan lines. In Chapter 11, Render Postprocessing, we’ll look at postprocessing and how you can apply it to your scene.