Working with Three.js Materials
local graph
Chapter 4 — Working with Three.js Materials
Section titled “Chapter 4 — Working with Three.js Materials”In Chapter 3, Working with Light Sources in Three.js, we talked a bit about materials. You learned that a material, together with a THREE.Geometry instance, forms a THREE.Mesh object. A material is like the skin of an object that defines what the outside of a geometry looks like. For example, a skin defines whether a geometry is metallic-looking, transparent, or shown as a wireframe. The resulting THREE.Mesh object can then be added to the scene to be rendered by Three.js.
So far, we haven’t looked at materials in much detail. In this chapter, we’ll dive into all the materials Three.js has to offer, and you’ll learn how you can use these materials to create good-looking 3D objects. The materials we’ll explore in this chapter are shown in the following list:
MeshBasicMaterial: This is a basic material that you can use to give your geometries a simple color or show the wireframe of your geometries. This material isn’t influenced by lights.MeshDepthMaterial: This is a material that uses the distance from the camera to determine how to color your mesh.MeshNormalMaterial: This is a simple material that bases the color of a face on its normal vector.MeshLambertMaterial: This is a material that takes lighting into account and is used to create dull, non-shiny-looking objects.MeshPhongMaterial: This is a material that also takes lighting into account and can be used to create shiny objects.MeshStandardMaterial: This is a material that uses physical-based rendering to render the object. With physical-based rendering, a physically correct model is used to determine how light interacts with a surface. This allows you to create more accurate and realistic-looking objects.MeshPhysicalMaterial: This is an extension ofMeshStandardMaterialthat allows more control over the reflection.MeshToonMaterial: This is an extension ofMeshPhongMaterialthat tries to make objects look hand-drawn.ShadowMaterial: This is a specific material that can receive shadows, but otherwise, it is rendered transparent.ShaderMaterial: This material allows you to specify shader programs to directly control how vertices are positioned and pixels are colored.LineBasicMaterial: This is a material that can be used on theTHREE.Linegeometry to create colored lines.LineDashMaterial: This is the same asLineBasicMaterial, but this material also allows you to create a dashed effect.
In the sources of Three.js, you can also find THREE.SpriteMaterial and THREE.PointsMaterial. These are materials you can use when styling individual points. We won’t discuss those in this chapter, but we’ll explore them in Chapter 7, Points and Sprites.
Materials have several common properties, so before we look at the first material, THREE.MeshBasicMaterial, we’ll look at the properties shared by all the materials.
Understanding common material properties
Section titled “Understanding common material properties”You can quickly see for yourself which properties are shared between all the materials. Three.js provides a material base class, THREE.Material, that lists all these common properties. We’ve divided these common material properties into the following three categories:
- Basic properties: These are the properties you’ll use most often. With these properties, you can, for instance, control the opacity of the object, whether it is visible, and how it is referenced (by ID or custom name).
- Blending properties: Every object has a set of blending properties. These properties define how the color of each point of the material is combined with the color behind it.
- Advanced properties: Several advanced properties control how the low-level WebGL context renders objects. In most cases, you won’t need to deal with these properties.
Note that, in this chapter, we will skip most of the properties related to textures and maps. Most materials allow you to use images as textures (for instance, a wood-like or stone-like texture). In Chapter 10, Loading and Working with Textures, we will dive into the various available texture and mapping options. Some materials also have specific properties related to animation (for example, skinning, morpNormals, and morphTargets); we’ll also skip those properties. These will be addressed in Chapter 9, Animations and Moving the Camera. The clipIntersection, clippingPlanes, and clipShadows properties will be addressed in Chapter 6, Exploring Advanced Geometries.
We will start with the first set shown in the list: the basic properties.
Basic properties
Section titled “Basic properties”The basic properties of the THREE.Material object are listed here (you will see these properties in action in the THREE.MeshBasicMaterial section):
id: This is used to identify a material and is assigned when you create a material. This starts at0for the first material and is increased by1for each additional material that is created.uuid: This is a uniquely generated ID and is used internally.name: You can assign a name to a material with this property. This can be used for debugging purposes.opacity: This defines how transparent an object is. Use this together with thetransparentproperty. The range of this property is from0to1.transparent: If this is set totrue, Three.js will render this object with the set opacity. If this is set tofalse, the object won’t be transparent, just more lightly colored. This property should also be set totrueif you use a texture that uses an alpha (transparency) channel.visible: This defines whether this material is visible. If you set this tofalse, you won’t see the object in the scene.side: With this property, you can define to which side of the geometry a material is applied. The default isTHREE.Frontside, which applies the material to the front (outside) of an object. You can also set this toTHREE.BackSide, which applies it to the back (inside), orTHREE.DoubleSide, which applies it to both sides.needsUpdate: When Three.js creates a material, it converts it into a set of WebGL instructions. When you want the changes you made in the material to also result in an update to the WebGL instructions, you can set this property totrue.colorWrite: If set tofalse, the color of this material won’t be shown (in effect, you’ll create invisible objects, which occlude objects behind them).flatShading: This determines whether this material is rendered using flat shading. With flat shading, the individual triangles that make up an object are rendered separately and aren’t combined into a smooth surface.lights: This is a Boolean value that determines whether this material is affected by lights. The default value istrue.premultipliedAlpha: This changes the way the transparency of an object is rendered. The default value isfalse.dithering: This applies a dithering effect to the rendering material. This can be used to avoid banding. The default value isfalse.shadowSide: This is just like thesideproperty but determines which side of the faces casts the shadows. If not set, this follows the value set on thesideproperty.vertexColors: With this property, you can define individual colors to be applied to each vertex. If set totrue, any color set on a vertex is used in rendering, while if set tofalse, the colors of the vertices aren’t used.fog: This property determines whether this material is affected by global fog settings. This is not shown in action, but if this is set tofalse, the global fog we saw in Chapter 2, Basic Components that Make up a Three.js Scene, is disabled.
For each material, you can also set several blending properties.
Blending properties
Section titled “Blending properties”Materials have a couple of generic blending-related properties. Blending determines how the colors we render interact with the colors that are behind them. We’ll touch upon this subject a little bit when we talk about combining materials. The blending properties are listed here:
blending: This determines how the material on this object blends with the background. The normal mode isTHREE.NormalBlending, which only shows the top layer.blendSrc: Besides using the standard blending modes, you can also create custom blend modes by settingblendsrc,blenddst, andblendequation. This property defines how an object (the source) is blended into the background (the destination). The defaultTHREE.SrcAlphaFactorsetting uses the alpha (transparency) channel for blending.blendSrcAlpha: This is the transparency ofblendSrc. The default isnull.blendDst: This property defines how the background (the destination) is used in blending and defaults toTHREE.OneMinusSrcAlphaFactor, which means this property also uses the alpha channel of the source for blending but uses1( the alpha channel of the source) as the value.blendDstAlpha: This is the transparency ofblendDst. The default isnull.blendEquation: This defines how theblendsrcandblenddstvalues are used. The default is to add them (AddEquation). With these three properties, you can create your own custom blend modes.
The last set of properties is mostly used internally and controls the specifics of how WebGL is used to render the scene.
Advanced properties
Section titled “Advanced properties”We won’t go into the details of these properties. These are related to how WebGL works internally. If you do want to know more about these properties, the OpenGL specification is a good starting point. You can find this specification at https://www.khronos.org/opengl/wiki. The following list provides a brief description of these advanced properties:
depthTest: This is an advanced WebGL property. With this property, you can enable or disable theGL_DEPTH_TESTparameter. This parameter controls whether the depth of a pixel is used to determine a new pixel’s value. Normally, you wouldn’t need to change this. More information can be found in the OpenGL specification we mentioned earlier.depthWrite: This is another internal property. This property can be used to determine whether this material affects the WebGL depth buffer. If you use an object for a 2D overlay (for example, a hub), you should set this property tofalse. Usually, though, you shouldn’t need to change this property.depthFunc: This function compares a pixel’s depth. This corresponds toglDepthFuncfrom the WebGL specifications.polygonOffset,polygonOffsetFactor, andpolygonOffsetUnits: With these properties, you can control thePOLYGON_OFFSET_FILLWebGL feature. These are normally not needed. For an explanation of what they do in detail, you can look at the OpenGL specification.Alphatest: This value can be set to a specific value (0to1). Whenever a pixel has an alpha value smaller than this value, it won’t be drawn. You can use this property to remove some transparency-related artifacts. You can set the precision for this material to one of the following WebGL values:highp,mediump, orlowp.
Now, let’s look at all the available materials so that you can see the effect these properties have on the rendered output.
Starting with simple materials
Section titled “Starting with simple materials”In this section, we’ll look at a few simple materials: MeshBasicMaterial, MeshDepthMaterial, and MeshNormalMaterial.
Before we look into the properties of these materials, here’s a quick note on how you can pass in properties to configure the materials. There are two options:
- You can pass in the arguments in the constructor as a parameter object, like this:
const material = new THREE.MeshBasicMaterial({color: 0xff0000,name: 'material-1',opacity: 0.5,transparency: true,...})
- Alternatively, you can create an instance and set the properties individually,
const material = new THREE.MeshBasicMaterial();material.color = new THREE.Color(0xff0000);material.name = 'material-1'; material.opacity = 0.5;material.transparency = true;
Usually, the best way is to use the constructor if we know all the properties’ values while creating the material. The arguments used in both of these styles use the same format. The only exception to this rule is the color property. In the first style, we can just pass in the hex value, and Three.js will create a THREE.Color object itself. In the second style, we have to explicitly create a THREE.Color object. In this book, we’ll use both of these styles.
Now, let’s look at the first of the simple materials: THREE.MeshBasicMaterial.
THREE.MeshBasicMaterial
Section titled “THREE.MeshBasicMaterial”MeshBasicMaterial is a very simple material that doesn’t take into account the lights that are available in the scene. Meshes with this material will be rendered as simple, flat polygons, and you also have the option to show the geometry’s wireframe. Besides the common properties we saw earlier regarding this material, we can set the following properties (once again, we will ignore the properties that are used for textures since we’ll discuss those in the chapter on textures):
color: This property allows you to set the color of the material.wireframe: This allows you to render the material as a wireframe. This is great for debugging purposes.vertexColors: When set totrue, this will take the color of the individual vertices into account when rendering the model.
In the previous chapters, we saw how to create materials and assign them to objects. For THREE.MeshBasicMaterial, we can do so like this:
const meshMaterial = new THREE.MeshBasicMaterial({color: 0x7777ff});This creates a new THREE.MeshBasicMaterial and initializes the color property to 0x7777ff (which is purple).
We’ve added an example that you can use to play around with the THREE.MeshBasicMaterial properties and the basic properties we discussed in the previous sections. If you open up the basic-mesh-material.html example in the chapter-04 folder, you’ll see a simple mesh on screen and a set of properties on the right of the scene that you can use to change models, add a simple texture, and change any of the material properties to see the effect immediately:

Figure 4.1 – Start screen for the basic material example
What you can see in this screenshot is a basic simple gray sphere. We already mentioned that THREE.MeshBasicMaterial doesn’t respond to lights, so you don’t see any depth; all the faces are the same color. Even with this material, though, you can still create nice-looking models. If you, for instance, enable the reflection by selecting the reflection property in the envMaps dropdown, set the background of the scene, and change the model to the torus model, you can already create great-looking models:

Figure 4.2 – Torus knot with an environment map
The wireframe property is a great one for looking at the underlying geometry of THREE.Mesh and works great for debugging:

Figure 4.3 – Model showing its wireframe
The final property that we want to look a bit closer at is vertexColors. If you enable this property, the colors of the individual vertices are used in rendering the model. If you select vertexColor from the model dropdown in the menu, you’ll see a model that has colored vertices. The easiest way to see this is by also enabling the wireframe:

Figure 4.4 – Model showing wireframe and vertex colors
Vertex colors can be used to color different parts of the mesh in different colors without having to use textures or multiple materials.
In this example, you can also play around with the standard material properties we discussed at the beginning of this chapter by looking at the THREE.Material section of the menu in Figure 4*.4*.
THREE.MeshDepthMaterial
Section titled “THREE.MeshDepthMaterial”The next material on the list is THREE.MeshDepthMaterial. With this material, the way an object looks isn’t defined by lights or by a specific material property – it is defined by the distance from the object to the camera. You can, for instance, combine this with other materials to easily create fading effects. The only additional property this material has is one we saw in THREE.MeshBasicMaterial: the wireframe property.
To demonstrate this material, we created an example that you can view by opening the mesh-depth-material example:

Figure 4.5 – Mesh depth material
In this example, you can add and remove cubes by clicking on the relevant buttons in the menu. What you’ll see is that the cubes that are close to the camera are rendered very bright, and those farther away from the camera are rendered less bright. In this example, you can see how this works by playing around with the properties of the Perspective Camera settings. By playing around with the far and near properties of the camera, you can change the brightness of all the cubes in the scene.
Normally, you wouldn’t use this material as the only material for a mesh; instead, you’d combine it with a different material. We’ll see how that works in the next section.
Combining materials
Section titled “Combining materials”If you look back at the properties of THREE.MeshDepthMaterial, you will see that there isn’t an option to set the color of the cubes. Everything was decided for you by the default properties of the material. Three.js, however, has the option to combine materials to create new effects (this is also where blending comes into play). The following code shows how we can combine materials:
import * as SceneUtils from 'three/examples/jsm/ utils/SceneUtils'const material1 = new THREE.MeshDepthMaterial()const material2 = new THREE.MeshBasicMaterial({ color: 0xffff00 })const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5)const cube = SceneUtils.createMultiMaterialObject(geometry, [material2, material1])First, we create our two materials. For THREE.MeshDepthMaterial, we don’t do anything special; for THREE.MeshBasicMaterial, we just set the color. The last line in this code fragment is also an important one. When we create a mesh with the SceneUtils.createMultiMaterialObject() function, the geometry gets copied and two of the same meshes are returned in a group.
We get the following green-colored cubes that use the brightness from THREE.MeshDepthMaterial and the color from THREE.MeshBasicMaterial. You can see how this works by opening the combining-materials.html example in the chapter-4 folder in your browser:

Figure 4.6 – Combining materials
When you open this example for the first time, you’ll just see the solid objects, without any effect from THREE.MeshDepthMaterial. To combine the colors, we also need to specify how these colors blend. In the menu on the right in Figure 4*.6*, you can specify this using the blending property. For this example, we’ve used the THREE.AdditiveBlending mode, which means the colors are added together, and the resulting color is shown. This example is a great way to play around with the different blending options, and see how they affect the final color of the material.
The next material is also one where we won’t have any influence on the colors used in rendering.
THREE.MeshNormalMaterial
Section titled “THREE.MeshNormalMaterial”The easiest way to understand how this material is rendered is by first looking at an example. Open up the mesh-normal-material.html example in the chapter-4 folder and enable flatShading:

Figure 4.7 – Mesh normal material
As you can see, each face of the mesh is rendered in a slightly different color. This happens because the color of each face is based on the normals pointing out from the face. And this face normal is based on the normal vector of the individual vertices that make up the face. A normal vector is perpendicular to the face of a vertex. The normal vector is used in many different parts of Three.js. It is used to determine light reflections, helps with mapping textures to 3D models, and provides information on how to light, shade, and color pixels on the surface. Luckily, though, Three.js handles the computation of these vectors and uses them internally, so you don’t have to calculate or deal with them yourselves.
Three.js comes with a helper to visualize this normal, and you can show this by enabling the vertexHelpers property in the menu:

Figure 4.8 – Mesh normal helpers
Adding this helper yourself can be done in a couple of lines of code:
Import { VertexNormalsHelper } from 'three/examples/jsm/ helpers/VertexNormalsHelper'...const helper = new VertexNormalsHelper(mesh, 0.1, 0xff0000)helper.name = 'VertexNormalHelper'scene.add(helper)VertexNormalsHelper takes three parameters. The first one is THREE.Mesh, for which you want to see the helpers, the second one is the length of the arrow, and the last one is the color.
Let’s take this example as an opportunity to look at the shading property. With the shading property, we can tell Three.js how to render our objects. If you use THREE.FlatShading, each face will be rendered as-is (as you can see in the previous following screenshot), or you can use THREE.SmoothShading, which smooths out the faces of our objects. For instance, if we render the same sphere using THREE.SmoothShading, the result will look like this:

Figure 4.9 – Mesh normal smooth shading
We’re done with the simple materials, but let’s look at one additional subject before moving on. In the next section, we’ll look at how you can use different materials for specific faces of a geometry.
Multiple materials for a single mesh
Section titled “Multiple materials for a single mesh”When creating THREE.Mesh, so far, we’ve used a single material. It is also possible to define a specific material for each of the faces of a geometry. For instance, if you have a cube that has 12 faces (remember, Three.js works with triangles), you can assign a different material (for example, with a different color) to each side of the cube. Doing this is straightforward, as shown in the following piece of code:
const mat1 = new THREE.MeshBasicMaterial({ color: 0x777777 })const mat2 = new THREE.MeshBasicMaterial({ color: 0xff0000 })const mat3 = new THREE.MeshBasicMaterial({ color: 0x00ff00 })const mat4 = new THREE.MeshBasicMaterial({ color: 0x0000ff })const mat5 = new THREE.MeshBasicMaterial({ color: 0x66aaff })const mat6 = new THREE.MeshBasicMaterial({ color: 0xffaa66 })const matArray = [mat1, mat2, mat3, mat4, mat5, mat6]const cubeGeom = new THREE.BoxGeometry(1, 1, 1, 10, 10, 10)const cubeMesh = new THREE.Mesh(cubeGeom, material)We create an array, named matArray, to hold all the materials, and use that array to create THREE.Mesh. What you might notice is that we only create six materials, even though we’ve got 12 faces. To understand how this works, we have to look at how Three.js assigns a material to a face. Three.js uses the groups property for this. To see this yourself, open up the source code for multi-material.js and add the debugger statement, like this:
const group = new THREE.Group()for (let x = 0; x < 3; x++) { for (let y = 0; y < 3; y++) { for (let z = 0; z < 3; z++) { const cubeMesh = sampleCube([mat1, mat2, mat3, mat4, mat5, mat6], 0.95) cubeMesh.position.set(x - 1.5, y - 1.5, z - 1.5) group.add(cubeMesh) debugger } }}This will cause the browser to stop executing, and allows you to inspect all the objects from the console of the browser:

Figure 4.10 – Using the debugger statement to stop execution
In the browser, if you open the Console tab, you can print our information about all different kinds of objects. So, if we want to see the details of cubeMesh, we can use console.log(cubeMesh):

Figure 4.11 – Printing out information about an object
If you look further into the geometry property of cubeMesh, you will see groups. This property is an array that consists of six elements, where each element contains the range of vertices that belong to that group, and an additional property called materialIndex that specifies which of the passed-in materials should be used for that group of vertices:
[{ "start": 0, "count": 600, "materialIndex": 0 }, { "start": 600, "count": 600, "materialIndex": 1 }, { "start": 1200, "count": 600, "materialIndex": 2 }, { "start": 1800, "count": 600, "materialIndex": 3 }, { "start": 2400, "count": 600, "materialIndex": 4 }, { "start": 3000, "count": 600, "materialIndex": 5 }]So, if you create your own objects from scratch, and want to apply different materials to different vertices groups, you have to make sure you set the groups property correctly. For the objects created by Three.js, you don’t have to do this manually, since Three.js already does this.
With this approach, it’s very simple to create interesting models. For instance, we can easily create a simple 3D Rubik’s Cube, as you can see in the multi-materials.html example:

Figure 4.12 – Multi-material with six different materials
We’ve also added controls for the materials that are applied to each side to experiment with. Creating this cube is not much different than what we saw in the Multiple materials for a single mesh section:
const group = new THREE.Group()const mat1 = new THREE.MeshBasicMaterial({ color: 0x777777 })const mat2 = new THREE.MeshBasicMaterial({ color: 0xff0000 })const mat3 = new THREE.MeshBasicMaterial({ color: 0x00ff00 })const mat4 = new THREE.MeshBasicMaterial({ color: 0x0000ff })const mat5 = new THREE.MeshBasicMaterial({ color: 0x66aaff })const mat6 = new THREE.MeshBasicMaterial({ color: 0xffaa66 })for (let x = 0; x < 3; x++) { for (let y = 0; y < 3; y++) { for (let z = 0; z < 3; z++) { const cubeMesh = sampleCube([mat1, mat2, mat3, mat4, mat5, mat6], 0.95) cubeMesh.position.set(x - 1.5, y - 1.5, z - 1.5) group.add(cubeMesh) } }}In this piece of code, first, we create THREE.Group, which will hold all the individual cubes (group); next, we create the materials for each side of the cube. Then, we create three loops to make sure we create the right number of cubes. In this loop, we create each of the individual cubes, assign the materials, position them, and add them to the group. What you should remember is that the position of the cubes is relative to the position of this group. If we move or rotate the group, all the cubes will move and rotate with it. For more information on how to work with groups, look at Chapter 8, Creating and Loading Advanced Meshes and Geometries.
And that wraps up this section on basic materials and how to combine them. In the following section, we’ll look at more advanced materials.
Advanced materials
Section titled “Advanced materials”In this section, we’ll look at the more advanced materials Three.js has to offer. We’ll look at the following materials:
THREE.MeshLambertMaterial: A material for rough-looking surfacesTHREE.MeshPhongMaterial: A material for shiny-looking surfacesTHREE.MeshToonMaterial: Renders the mesh in a cartoon-like fashionTHREE.ShadowMaterial: A material that only shows shadows cast on it; the material is otherwise is transparentTHREE.MeshStandardMaterial: A versatile material that can be used to represent many different kinds of surfacesTHREE.MeshPhysicalMaterial: Similar toTHREE.MeshStandardMaterialbut provides additional properties for more real-world-like surfacesTHREE.ShaderMaterial: A material where you can define for yourself how to render the object by writing your own shaders
We’ll start with THREE.MeshLambertMaterial.
THREE.MeshLambertMaterial
Section titled “THREE.MeshLambertMaterial”This material can be used to create dull-looking, non-shiny surfaces. This is a very easy-to-use material that responds to the lighting sources in the scene. This material can be configured with the basic properties we’ve already seen, so we won’t go into the details of those properties; instead, we will focus on the ones specific to this material. That just leaves us with the following properties:
color: This is the color of the material.emissive: This is the color the material emits. It doesn’t act as a light source, but this is a solid color that is unaffected by other lighting. This defaults to black. You can use this to create objects that look like they glow.emissiveIntensity: The intensity with which the object seems to glow.
Creating this object follows the same approach we’ve seen for the other materials:
const material = new THREE.MeshLambertMaterial({color: 0x7777ff});For an example of this material, look at the mesh-lambert-material.html example:

Figure 4.13 – Mesh lambert material
This screenshot shows a torus knot, in white, with a very light red emissive glow. One of the interesting features of THREE.LambertMaterial is that it also supports the wireframe properties, so you can render a wireframe that responds to the lights in the scene:

Figure 4.14 – Mesh Lambert material with a wireframe
The next material works in pretty much the same way but can be used to create shiny objects.
THREE.MeshPhongMaterial
Section titled “THREE.MeshPhongMaterial”With THREE.MeshPhongMaterial, we can create a shiny material. The properties you can use for that are pretty much the same as for a non-shiny THREE.MeshLambertMaterial object. In older versions, this was the only material that you could use to make shiny, plastic, or metal-like objects. With newer versions of Three.js, if you want more control, you can also use THREE.MeshStandardMaterial and THREE.MeshPhysicalMaterial. We’ll discuss both of these materials after we look at THREE.MeshPhongMaterial.
We’ll once again skip the basic properties and focus on the properties specific to this material. The properties of this material are listed here:
emissive: This is the color this material emits. It doesn’t act as a light source, but this is a solid color that is unaffected by other lighting. This defaults to black.emissiveIntensity: The intensity with which the object seems to glow.specular: This property defines how shiny the material is and with what color it shines. If this is set to the same color as thecolorproperty, you get a more metallic-looking material. If this is set to gray, it results in a more plastic-looking material.shininess: This property defines how shiny the specular highlight is. The default value forshininessis30. The higher this value is, the shinier the object is.
Initializing a THREE.MeshPhongMaterial material is done in the same way as we’ve already seen for all the other materials and is shown in the following line of code:
const meshMaterial = new THREE.MeshPhongMaterial({color: 0x7777ff});To give you the best comparison, we will keep using the same models for this material as we did for THREE.MeshLambertMaterial and the other materials in this chapter. You can use the control GUI to play around with this material. For instance, the following settings create a plastic-looking material. You can find this example in mesh-phong-material.html:

Figure 4.15 – Mesh Phong material with high shininess
As you can see from this screenshot, the object is more shiny and plastic compared to what we saw with THREE.MeshLambertMaterial.
THREE.MeshToonMaterial
Section titled “THREE.MeshToonMaterial”Not all the materials Three.js provides are practical. For instance, THREE.MeshToonMaterial allows you to render an object in a cartoon-like style (see the mesh-toon-material.html example):

Figure 4.16 – The fox model rendered with MeshToonMaterial
As you can see, it looks a little bit like what we saw with THREE.MeshBasicMaterial, but this material responds to the lights in the scene and supports shadows. It just bands colors together to create a cartoon-like effect.
If you want more realistic materials, THREE.MeshStandardMaterial is a good choice.
THREE.MeshStandardMaterial
Section titled “THREE.MeshStandardMaterial”THREE.MeshStandardMaterial is a material that takes a physics approach to determine how to react to the lighting in the scene. It is a great material for shiny and metal-like materials, and provides several properties you can use to configure this material:
metalness: This property determines how metal-like a material is. Non-metallic materials should use a value of0, whereas metallic materials should use a value close to 1. The default is0.5.roughness: You can also set how rough the material is. This determines how the light that hits this material is diffused. The default is0.5. A value of0is a mirror-like reflection, whereas a value of1diffuses all the light.
Besides these properties, you can also use the color and emissive properties, as well as the properties from THREE.Material, to alter this material. As you can see in the following screenshot, we can use these properties to simulate a kind of brushed metal look by playing around with the metalness and roughness parameters:

Figure 4.17 – Creating a brushed metal effect with MeshStandardMaterial
Three.js provides a material that provides even more settings to render real-looking objects: THREE.MeshPhysicalMaterial.
THREE.MeshPhysicalMaterial
Section titled “THREE.MeshPhysicalMaterial”A material very close to THREE.MeshStandardMaterial is THREE.MeshPhysicalMaterial. With this material, you have more control over the reflectivity of the material. This material provides, besides the properties we’ve already seen for THREE.MeshPhysicalMaterial, the following properties to help you control what the material looks like:
clearCoat: A value indicating a coating layer on top of the material. The higher this value is, the more coating is applied, and the more effective theclearCoatRoughnessparameter is. This value ranges from0to1with a default of0.clearCoatRoughness: The roughness used for the coating of the material. The rougher it is, the more light is diffused. This is used together with theclearCoatproperty. This value ranges from0to1with a default of0.
As we’ve seen for other materials, it is quite hard to reason about the values you should use for your specific requirements. It’s often the best choice to add a simple UI (as we do in the examples) and play around with the values to get to a combination that best reflects your needs. You can see this example in action by looking at the mesh-physical-material.html example:

Figure 4.18 – Mesh physical material using a clear coat to control reflection
Most of the advanced materials cast and receive shadows. The next material we’re going to have a quick look at is a bit different than most. This material doesn’t render the object itself, but only shows the shadows.
THREE.ShadowMaterial
Section titled “THREE.ShadowMaterial”THREE.ShadowMaterial is a special material that doesn’t have any properties. You can’t set the color or the shininess, or anything else. The only thing this material does is render the shadow the mesh would receive. The following screenshot should explain this:

Figure 4.19 – Shadow material just rendering the shadows the mesh receives
Here, the only thing we can see are the shadows the object receives, nothing else. This material can, for instance, be combined with your own materials without you having to determine how to receive shadows.
The last of the advanced materials we’ll explore is THREE.ShaderMaterial.
Using your own shaders with THREE.ShaderMaterial
Section titled “Using your own shaders with THREE.ShaderMaterial”THREE.ShaderMaterial is one of the most versatile and complex materials available in Three.js. With this material, you can pass in your own custom shaders that are directly run in the WebGL context. A shader converts Three.js JavaScript meshes into pixels on the screen. With these custom shaders, you can define exactly how your object should be rendered and how to override or alter the defaults from Three.js. In this section, we won’t go into too much detail on how to write custom shaders; instead, we will just show you a couple of examples.
As we’ve already seen, THREE.ShaderMaterial has several properties you can set. With THREE.ShaderMaterial, Three.js passes in all the information regarding these properties to your custom shaders, but you still have to process the information to create colors and vertex positions. The following are the properties of THREE.Material that are passed into the shader, and that you can interpret for yourself:
wireframe: This renders the material as a wireframe. This is great for debugging purposes.shading: This defines how shading is applied. The possible values areTHREE.SmoothShadingandTHREE.FlatShading. This property isn’t enabled in the example for this material. For an example, look at the THREE. MeshNormalMaterial section.vertexColors: You can define individual colors to be applied to each vertex with this property. Look at theLineBasicMaterialexample in the THREE.LineBasicMaterial section, where we use this property to color the various parts of a line.fog: This determines whether this material is affected by global fog settings. This is not shown in action. If this is set tofalse, the global fog we saw in Chapter 2 doesn’t affect how this object is rendered.
Besides these properties that are passed into the shader, THREE.ShaderMaterial also provides several specific properties you can use to pass in additional information into your custom shader. Once again, we won’t go into too much detail on how you can write your own shaders, since that would be a book on its own, so we’ll just cover the basics:
fragmentShader: This shader defines the color of each pixel that is passed in. Here, you need to pass in the string value of your fragment shader program.vertextShader: This shader allows you to change the position of each vertex that is passed in. Here, you need to pass in the string value of your vertex shader program.uniforms: This allows you to send information to your shader. The same information is sent to each vertex and fragment.defines: Converts custom key value pairs as#definecode fragments. With these fragments, you can set some additional global variables in the shader programs or define your own custom global constants.attributes: These can change between each vertex and fragment. They are usually used to pass positional and normal-related data. If you want to use this property, you need to provide information for all the vertices of the geometry.lights: This determines whether light data should be passed into the shaders. This defaults tofalse.
Before we look at an example, we’ll provide a quick explanation of the most important parts of THREE.ShaderMaterial. To work with this material, we have to pass in two different shaders:
vertexShader: This is run on each vertex of the geometry. You can use this shader to transform the geometry by moving the position of the vertices around.fragmentShader: This is run on each fragment of the geometry. InfragmentShader, we return the color that should be shown for this specific fragment.
For all the materials we’ve discussed so far in this chapter, Three.js provides fragmentShader and vertexShader, so you don’t have to worry about them and pass them in explicitly.
In this section, we’ll look at a simple example that uses a very simple vertexShader program that changes the x and y coordinates of the vertices of a simple THREE.PlainGeometry and a fragmentShader program that changes the color based on some input.
Up next, you can see the complete code for our vertexShader. Note that writing shaders isn’t done in JavaScript. You write shaders in a C-like language called GLSL (WebGL supports OpenGL ES Shading Language 1.0 — for more information on GLSL, see https://www.khronos.org/webgl/). The code for our simple shader looks like this:
uniform float time;void main(){ vec3 posChanged=position; posChanged.x=posChanged.x*(abs(sin(time*2.))); posChanged.y=posChanged.y*(abs(cos(time*1.))); posChanged.z=posChanged.z*(abs(sin(time*.5))); gl_Position=projectionMatrix*modelViewMatrix*vec4 (posChanged,1.);}We won’t go into too much detail here and just focus on the most important parts of this code. To communicate with the shaders from JavaScript, we use something called uniforms. In this example, we use the uniform float time; statement to pass in an external value.
Based on this value, we change the x, y, and z coordinates of the passed-in vertex (which is passed in as the position variable):
posChanged.x=posChanged.x*(abs(sin(time*2.)));posChanged.y=posChanged.y*(abs(cos(time*1.)));posChanged.z=posChanged.z*(abs(sin(time*.5)));The posChanged vector now contains the new coordinate for this vertex based on the passed-in time variable. The last step we need to perform is to pass this new position back to the renderer, which is always done like this for Three.js:
gl_Position=projectionMatrix*modelViewMatrix*vec4 (posChanged,1.);The gl_Position variable is a special variable that is used to return the final position. This program is passed as a string value to the vertexShader property of THREE.ShaderMaterial. For fragmentShader, we do something similar. We’ve created a very simple fragment shader that just flips through colors based on the passed-in time uniform:
uniform float time;void main(){ float c1=mod(time,.5); float c2=mod(time,.7); float c3=mod(time,.9); gl_FragColor=vec4(c1,c2,c3,1.);}What we do in a fragmentShader is determine the color of a passed-in fragment (a pixel). The real shader programs take a lot into account, such as lights, the position of the vertex on the face, normals, and more. In this example, though, we just determine the rgb values of a color and return that in gl_FragColor, which is then shown on the final rendered mesh.
Now, we need to glue the geometry, the material, and the two shaders together. In Three.js, we can do that like this:
const geometry = new THREE.PlaneGeometry(10, 10, 100, 100)const material = new THREE.ShaderMaterial({ uniforms: { time: { value: 1.0 } }, vertexShader: vs_simple, fragmentShader: fs_simple})const mesh = new THREE.Mesh(geometry, material)Here, we define the time uniform, which will contain a value available in the shaders, and define vertexShader and fragmentShader as strings that we want to use. The only thing we need to do is make sure we change the time uniform in the render loop, and that’s it:
// in the renderloopmaterial.uniforms.time.value += 0.005In the examples for this chapter, we’ve added a couple of simple shaders to experiment with. You will see the results if you open up the shader-material-vertex.html example in the chapter-4 folder:

Figure 4.20 – A shader material that shows a plane with the two example shader programs
In the dropdown menu, you can also find a couple of other shaders. For instance, the fs_night_sky fragment shader shows a starry night (based on the shader from https://www.shadertoy.com/view/Nlffzj). When combined with vs_ripple, you get a very nice-looking effect, completely running on the GPU, as shown here:

Figure 4.21 – Rippling effect with a starry night fragment shader
It is possible to combine existing materials and reuse their fragment and vertex shaders with your own shaders. That way, you can, for instance, extend THREE.MeshStandardMaterial with some custom effects. Doing this in plain Three.js, however, is rather difficult to do and very error prone. Luckily, there is an open source project that provides us with a custom material that makes it very easy to wrap existing materials and add our own custom shaders. In the next section, we’ll have a quick look at how that works.
Customizing existing shaders with CustomShaderMaterial
Section titled “Customizing existing shaders with CustomShaderMaterial”THREE.CustomShader doesn’t come with the default Three.js distribution, but since we’re using yarn, it is really easy to install (this is what you did when running the relevant commands from Chapter 1, Creating Your First 3D Scene wth Three.js). If you want more information on this module, you can check out https://github.com/FarazzShaikh/THREE-CustomShaderMaterial, where you can find documentation and additional examples.
First, let’s have a quick look at the code before we show some examples. Using THREE.CustomShader is the same as using the other materials:
const material = new CustomShaderMaterial({ baseMaterial: THREE.MeshStandardMaterial, vertexShader: ..., fragmentShader: ..., uniforms: { time: { value: 0.2 }, resolution: { value: new THREE.Vector2() } }, flatShading: true, color: 0xffffff})As you can see, it is a bit of a combination of a normal material and a THREE.ShaderMaterial. The main thing to look at is the baseMaterial property. Here, you can add any of the standard Three.js materials. Any additional property you add, besides vertexShader, fragmentShader, and uniforms, gets applied to this baseMaterial. The vertexshader, fragmentShader, and uniforms properties work in the same way as we’ve seen for THREE.ShaderMaterial.
Out of the box, we need to make a couple of small changes to our shaders themselves. Recall the Using your own shaders with THREE.ShaderMaterial section, where we used gl_Position and gl_FragColor to set the final output of the position of a vertex and the color of a fragment. With this material, we use csm_Position for the final position and csm_DiffuseColor for the color. There are a couple more output variables you can use, which are explained in more detail here: https://github.com/FarazzShaikh/THREE-CustomShaderMaterial#output-variables.
If you open the custom-shader-material example, you will see how our simple shaders can be used together with the default materials from Three.js:

Figure 4.22 – Ripple effect with an environment map using MeshStandardMaterials as the base
This approach gives you a relatively easy way to create your custom shaders, without having to start completely from scratch. You can just reuse the lights and shadow effects from the default shaders and extend them with your custom-needed functionality.
So far, we’ve looked at materials that work with meshes. Three.js also provides materials that can be used together with line geometries. In the next section, we’ll explore those materials.
Materials you can use for a line geometry
Section titled “Materials you can use for a line geometry”The last couple of materials we’re going to look at can only be used on one specific mesh: THREE.Line. As the name implies, this is just a single line that only consists of lines and doesn’t contain any faces. Three.js provides two different materials you can use on a THREE.Line geometry, as follows:
THREE.LineBasicMaterial: This basic material for a line allows you to set thecolorandvertexColorsproperties.THREE.LineDashedMaterial: This has the same properties asTHREE.LineBasicMaterialbut allows you to create a dashed line effect by specifyingdashandspacingsizes.
We’ll start with the basic variant; after that, we’ll look at the dashed variant.
THREE.LineBasicMaterial
Section titled “THREE.LineBasicMaterial”The materials that are available for the THREE.Line geometry are very simple. It inherits all of the properties from THREE.Material, but the following are the properties that are most important for this material:
color: This determines the color of the line. If you specifyvertexColors, this property is ignored. An example of how to do this is shown in the following code fragment.vertexColors: You can supply a specific color for each vertex by setting this property to theTHREE.VertexColorsvalue.
Before we look at an example of THREE.LineBasicMaterial, let’s have a quick look at how we can create a THREE.Line mesh from a set of vertices and combine that with THREE.LineMaterial to create the mesh, as shown in the following code:
const points = gosper(4, 50)const lineGeometry = new THREE.BufferGeometry(). setFromPoints(points)const colors = new Float32Array(points.length * 3)points.forEach((e, i) => { const color = new THREE.Color(0xffffff) color.setHSL(e.x / 100 + 0.2, (e.y * 20) / 300, 0.8) colors[i * 3] = color.r colors[i * 3 + 1] = color.g colors[i * 3 + 2] = color.b})lineGeometry.setAttribute('color', new THREE. BufferAttribute(colors, 3, true))const material = new THREE.LineBasicMaterial(0xff0000);const mesh = new THREE.Line(lineGeometry, material)mesh.computeLineDistances()The first part of this code fragment, const points = gosper(4, 60), is used as an example to get a set of x, y, and z coordinates. This function returns a Gosper curve (for more information, check out https://mathworld.wolfram.com/Peano-GosperCurve.html), which is a simple algorithm that fills a 2D space. What we do next is create a THREE.BufferGeometry instance and call the setFromPoints function to add the generated points. For each coordinate, we also calculate a color value that we use to set the color attribute of the geometry. Note mesh.computeLineDistances at the end of this code fragment. This is needed when you want to have dashed lines when using THREE.LineDashedMaterial.
Now that we have our geometry, we can create THREE.LineBasicMaterial and use this together with the geometry to create a THREE.Line mesh. You can see the result in the line-basic-material.html example. The following screenshot shows this example:

Figure 4.23 – Line basic material
This is a line geometry created with THREE.LineBasicMaterial. If we enable the vertexColors property, we will see that the individual line segments are colored:

Figure 4.24 – Line basic material with vertex colors
The next and last material we’ll discuss in this chapter is only slightly different from THREE.LineBasicMaterial. With THREE.LineDashedMaterial, not only can we color lines, but we can also add spaces to those lines.
THREE.LineDashedMaterial
Section titled “THREE.LineDashedMaterial”This material has the same properties as THREE.LineBasicMaterial and three additional ones you can use to define the dash width and the width of the gaps between the dashes:
scale: This scalesdashSizeandgapSize. If the scale is smaller than1,dashSizeandgapSizeincrease, whereas if the scale is larger than1,dashSizeandgapSizedecrease.dashSize: This is the size of the dash.gapSize: This is the size of the gap.
This material works almost exactly like THREE.LineBasicMaterial. The only difference is that you have to call computeLineDistances() (which is used to determine the distance between the vertices that make up a line). If you don’t do this, the gaps won’t be shown correctly. An example of this material can be found in line-dashed-material.html and looks like this:

Figure 4.25 – A Gosper mesh with the line dashed material
That’s it for this section on materials used for lines. You’ve seen that Three.js only provides a few materials specifically for line geometries, but with these materials, especially in combination with vertexColors, you should be able to style the line geometries any way you want.
Summary
Section titled “Summary”Three.js gives you a lot of materials you can use to skin your geometries. The materials range from the very simple (THREE.MeshBasicMaterial) to the complex (THREE.ShaderMaterial), where you can provide your own vertexShader and fragmentShader programs. Materials share a lot of basic properties. If you know how to use a single material, you’ll probably also know how to use the other materials. Note that not all materials respond to the lights in your scene. If you want a material that takes lighting into effect, you can usually just use THREE.MeshStandardMaterial. If you need more control, you can also look at THREE.MeshPhysicalMaterial, THREE.MeshPhongMaterial, or THREE.MeshLamberMaterial. Determining the effect of certain material properties from just code is very hard. Often, a good idea is to use the control GUI approach to experiment with these properties, as we showed in this chapter.
Also, remember that most of the properties of a material can be modified at runtime. Some, though (for example, side), can’t be modified at runtime. If you change such a value, you need to set the needsUpdate property to true. For a complete overview of what can and cannot be changed at runtime, see the following page: https://threejs.org/docs/#manual/en/introduction/How-to-update-things.
In this and the previous chapters, we talked about geometries. We used these in our examples and explored a couple of them. In the next chapter, you’ll learn everything about geometries and how you can work with them.