Working with Light Sources in Three.js
local graph
Chapter 3 — Working with Light Sources in Three.js
Section titled “Chapter 3 — Working with Light Sources in Three.js”In Chapter 1, Creating Your First 3D Scene with Three.js, you learned about the basics of Three.js, and in Chapter 2, The Basic Components that Make up a Three.js Application, we looked a bit deeper at the most important parts of the scene: the geometries, meshes, and cameras. You might have noticed that we skipped exploring the details of lights in that chapter, even though they make up an important part of every Three.js scene. Without lights, we won’t see anything rendered (unless we use basic or wireframe materials). Since Three.js contains several different light sources, each of which has a specific use, we’ll use this chapter to explain the various details of lights and prepare you for the upcoming chapters on material usage. By the end of this chapter, you’ll know the differences between the available lights and be able to choose and configure the correct light for your scene.
Note
WebGL itself doesn’t have inherent support for lighting. Without Three.js, you would have to write specific WebGL shader programs to simulate these kinds of lights, which is quite difficult. A good introduction to simulating lighting in WebGL from scratch can be found at https://developer.mozilla.org/en-US/docs/Web/WebGL/Lighting_in_WebGL.
In this chapter, we will cover the following topics:
- Different kinds of lighting in Three.js
- Working with basic lights
- Working with special lights
As with all the chapters, we have a lot of examples that you can use to experiment with the behavior of lights. The examples shown in this chapter can be found in the chapter-03 folder of the supplied sources.
What lighting types are provided in Three.js?
Section titled “What lighting types are provided in Three.js?”Several different lights are available in Three.js that all have specific behavior and usages. In this chapter, we’ll discuss the following set of lights:
THREE.AmbientLight: This is a basic light, the color of which is added to the current color of the objects in the scene.THREE.PointLight: This is a single point in space from which light spreads in all directions. This light can be used to create shadows.THREE.SpotLight: This light source has a cone-like effect like that of a desk lamp, a spotlight in the ceiling, or a torch. This light can cast shadows.THREE.DirectionalLight: This is also called infinite light. The light rays from this light can be seen as parallel, similar to the light from the Sun. This light can also be used to create shadows.THREE.HemisphereLight: This is a special light and can be used to create more natural-looking outdoor lighting by simulating a reflective surface and a faintly illuminating sky. This light also doesn’t provide any shadow-related functionality.THREE.RectAreaLight: With this light source, instead of a single point in space, you can specify an area from which light emanates.THREE.RectAreaLightdoesn’t cast any shadows.THREE.LightProbe: This is a special kind of light source where, based on the environment map used, a dynamic ambient light source is created to light the scene.THREE.LensFlare: This is not a light source, but withTHREE.LensFlare, you can add a lens flare effect to the lights in your scene.
This chapter is divided into two main parts. First, we’ll look at the basic lights: THREE.AmbientLight, THREE.PointLight, THREE.SpotLight, and THREE.DirectionalLight. All these lights extend the base THREE.Light object, which provides shared functionality. The lights mentioned here are simple lights that require little setup and can be used to recreate most of the required lighting scenarios. In the second part, we will look at a couple of special-purpose lights and effects: THREE.HemisphereLight, THREE.RectAreaLight, THREE.LightProbe, and THREE.LensFlare. You’ll probably only need these lights in very specific cases.
Working with basic lights
Section titled “Working with basic lights”We’ll start with the most basic of the lights: THREE.AmbientLight.
THREE.AmbientLight
Section titled “THREE.AmbientLight”When you create a THREE.AmbientLight, the color is applied globally. There isn’t a specific direction this light comes from, and THREE.AmbientLight doesn’t contribute to any shadows. You would normally not use THREE.AmbientLight as the single source of light in a scene since it applies its color to all the objects in the scene in the same way, regardless of the shape of the mesh. You use it together with other lighting sources, such as THREE.SpotLight or THREE.DirectionalLight, to soften the shadows or add some additional color to the scene. The easiest way to understand this is by looking at the ambient-light.html example in the chapter-03 folder. In this example, you get a simple user interface that can be used to modify the THREE.AmbientLight object that is available in this scene.
In the following screenshots, you can see that we used a simple waterfall model, and made the color and intensity properties of the used THREE.AmbientLight object configurable. In this first screenshot, you can see what happens when we set the color of the light to red:

Figure 3.1 – Ambient light set to red
As you can see, each element in our scene now has a red color added to its original color. And if we change the color to blue, we’ll get something like this:

Figure 3.2 – Ambient light set to blue
As this screenshot shows, the blue color is applied to all the objects and casts a glow over the complete scene. What you should remember when working with this light is that you should be very conservative with the color you specify. If the color you specify is too bright, you’ll quickly get a completely oversaturated image. Besides the color, we can also set the intensity property of the light. This property determines how much THREE.AmbientLight affects the colors in the scene. If we turn it down, only a little of the color is applied to the objects in the scene. If we turn it up, our scene becomes really bright:

Figure 3.3 – Ambient light set to red with high intensity
Now that we’ve seen what it does, let’s look at how you can create and use a THREE.AmbientLight. The following lines of code show you how to create a THREE.AmbientLight:
const color = new THREE.Color(0xffffff);const light = new THREE.AmbientLight(color);scene.add(light);Creating a THREE.AmbientLight is very simple and only takes a couple of steps. THREE.AmbientLight doesn’t have a position and is applied globally, so we only need to specify the color and add this light to the scene. Optionally, we can also provide an additional value in this constructor for the intensity of this light. Since we didn’t specify it here, it uses a default intensity of 1.
Note that in the previous code fragment, we passed in an explicit THREE.Color object to the constructor of THREE.AmbientLight. We could have also passed in the color as a string – for example, "rgb(255, 0, 0)" or "hsl(0, 100%, 50%)" – or as a number, as we did in the previous chapters: 0xff0000. More information on this can be found in the Using the THREE.Color object section.
Before we discuss THREE.PointLight, THREE.SpotLight, and THREE.DirectionalLight, first, let’s highlight their main difference – that is, how they emit light. The following diagram shows how these three light sources emit light:

Figure 3.4 – How different light sources emit light
You can see the following from this diagram:
THREE.PointLightemits light from a specific point in all directionsTHREE.SpotLightemits light from a specific point in a cone-like shapeTHREE.DirectionalLightdoesn’t emit light from a single point but emits light rays from a 2D plane, where the rays are parallel to each other
We’ll look at these light sources in more detail in the next few sections. Let’s start with THREE.SpotLight.
THREE.SpotLight
Section titled “THREE.SpotLight”THREE.SpotLight is one of the lights you’ll use often (especially if you want to use shadows). THREE.SpotLight is a light source that has a cone-like effect. You can compare this with a flashlight or a lantern. This light source has a direction and an angle at which it produces light. The following screenshot shows what a THREE.SpotLight looks like (spotlight.html):

Figure 3.5 – Spotlight lighting a scene
The following table lists all the properties that you can use to finetune THREE.SpotLight. First, we’ll look at the properties specific to the light’s behavior:
| Name | Description |
|---|---|
Angle | Determines how wide the beam emerging from the light is. The width is measured in radians and defaults to Math.PI/3. |
castShadow | If set to true, the light to which the property is applied will create shadows. See the following table on how to configure the shadows. |
Color | Indicates the color of the light. |
decay | Indicates the amount the light intensity diminishes the farther you move away from the light source. A decay of 2 leads to more realistic light, and the default value is 1. This property is only effective when the physicallyCorrectLights property is set on WebGLRenderer. |
distance | When this property is set to a non- 0 value, the light intensity will decrease linearly from the set intensity at the light’s position to 0 at the specified distance. |
intensity | Indicates the intensity with which the light shines. The property’s default value is 1. |
penumbra | Indicates the percentage at the edge of the spotlight’s coin, which is smoothed (blurred) to 0. It takes a value between 0 and 1, where the default is 0. |
power | Denotes the light’s power when rendered in the physically correct mode (enable this by setting the physicallyCorrectLights property set on WebGLRenderer). This property is measured in lumens and the default value is 4*Math.PI. |
position | Indicates the position of a light in THREE.Scene. |
target | With THREE.SpotLight, the direction the light is pointed in is important. With the target property, you can point THREE.SpotLight to look at a specific object or position in the scene. Note that this property requires a THREE.Object3D object (such as a THREE.Mesh). This is in contrast to the cameras we saw in Chapter 2, which use THREE.Vector3 in their lookAt function. |
visible | If this property is set to true (the default), the light is turned on, while if it is set to false, the light is turned off. |
Figure 3.6 – Properties of the THREE.SpotLight object
When you enable the shadow for THREE.SpotLight, you can control how that shadow is rendered. You can control this through the shadow property of a THREE.SpotLight, which can comprise the following:
| Name | Description |
|---|---|
shadow.bias | Moves the cast shadow away or toward the object casting the shadow. You can use this to solve some strange effects when you work with very thin objects. If you see strange shadow effects on your models, small values (for example, 0.01) for this property can often resolve the issue. The default value for this property is 0. |
shadow.camera.far | Determines from what distance from the light shadows should be created. The default value is 5000. Note that you can also set all the other properties provided for THREE.PerspectiveCamera, which we showed in Chapter 2. |
shadow.camera.fov | Determines how large the field of view used to create shadows is (see the Using different cameras for different scenes section in Chapter 2). The default value is 50. |
shadow.camera.near | Determines from what distance from the light shadows should be created. The default value is 50. |
shadow.mapSize.width and shadow.mapSize.height | Determine how many pixels are used to create a shadow. Increase these when a shadow has jagged edges or doesn’t look smooth. This can’t be changed after the scene has been rendered. The default value for both is 512. |
shadow.radius | When this value is set higher than 1, the edge of the shadows will be blurred. This won’t have any effect if the shadowMap.type property of THREE.WebGlRenderer is set to THREE.BasicShadowMap. |
Figure 3.7 – Shadow properties of the THREE.SpotLight object
Creating THREE.SpotLight is very easy. Just specify the color, set the properties you want, and add it to the scene, as follows:
const spotLight = new THREE.SpotLight("#ffffff")spotLight.penumbra = 0.4;spotLight.position.set(10, 14, 5);spotLight.castShadow = true;spotLight.intensity = 1;spotLight.shadow.camera.near = 10;spotLight.shadow.camera.far = 25;spotLight.shadow.mapSize.width = 2048;spotLight.shadow.mapSize.height = 2048;spotLight.shadow.bias = -0.01;scene.add(spotLight.target);Here, we create an instance of THREE.SpotLight and set the various properties to configure the light. We also explicitly set the castShadow property to true because we want shadows. We also need to point THREE.SpotLight somewhere, which we do with the target property. Before we can use this property, we first need to add the default target of the light to the scene, as follows:
scene.add(spotLight.target);By default, the target will be set to (0, 0, 0). In the example for this section, you can change the location of the target property and see that the light follows the position of this object:

Figure 3.8 – Spotlight pointing to a target
Note that you can also set the target of the light to an object in the scene. In that case, the direction of the light will be pointed to that object. If the object that the light is pointed at moves around, the light will keep pointing at that object.
In the table at the beginning of this section, we showed a couple of properties that can be used to control how the light emanates from THREE.SpotLight. The distance and angle properties define the shape of the cone of light. The angle property defines the width of the cone, and with the distance property, we set the length of the cone. The following diagram explains how these two values define the area that will receive light from THREE.SpotLight:

Figure 3.9 – Spotlight angle and distance
Usually, you won’t need to set these values since they come with reasonable defaults, but you can use these properties, for instance, to create a THREE.SpotLight instance that has a very narrow beam or quickly decreases in light intensity. The last property you can use to change the way THREE.SpotLight produces light is the penumbra property. With this property, you set from what position the intensity of the light decreases at the edge of the light cone. In the following screenshot, you can see the result of the penumbra property in action. We have a very bright light (high intensity) that rapidly decreases in intensity as it reaches the edge of the cone:

Figure 3.10 – Spotlight with a hard penumbra
Sometimes, it can be difficult to determine the correct settings for your lights, just by looking at the rendered scene. You might want to finetune the area that is lit for performance reasons or try and move the light around to a very specific location. This can be achieved by using THREE.SpotLightHelper:
const spotLightHelper = new THREE.SpotLightHelper (spotLight);scene.add(spotLightHelper)// in the render loopspotLightHelper.update();With the preceding code, you get an outline that shows the details of the spotlight, and can help in debugging and correctly positioning and configuring your light:

Figure 3.11– Spotlight with the helper enabled
Before moving on to the next light source, we’ll quickly look at the shadow-related properties available for a THREE.SpotLight object. You’ve already learned that we can get shadows by setting the castShadow property of a THREE.SpotLight instance to true. You also know that a THREE.Mesh object has two shadow-related properties. You set the castShadow property for objects that should cast shadows, and you use the receiveShadow property for objects that should show a shadow. Three.js also allows you very fine-grained control over how the shadow is rendered. This is done by a couple of the properties we explained in the table at the beginning of this section. With shadow.camera.near, shadow.camera.far, and shadow.camera.fov, you can control how and where this light casts a shadow. For a THREE.SpotLight instance, you can’t set shadow.camera.fov directly. This property is based on the angle property of THREE.SpotLight. This works in the same way as the perspective camera’s field of view, which we explained in Chapter 2. The easiest way to see this in action is by adding a THREE.CameraHelper; you can do this by checking the menu’s shadow-helper checkbox and playing around with the camera settings. As you can see in the following screenshot, selecting this checkbox shows the area that is used to determine the shadows for this light:

Figure 3.12 – Spotlight with the shadow helper enabled
When debugging issues with shadows, adding THREE.CameraHelper is useful. To do this, just add the following lines:
const shadowCameraHelper = new THREE.CameraHelper (spotLight.shadow.camera);scene.add(shadowCameraHelper);// in the render loopshadowCameraHelper.update();I’ll end this section with a couple of pointers, just in case you run into issues with shadows.
If the shadow looks blocky, you can increase the shadow.mapSize.width and shadow.mapSize.Height properties and make sure the area that is used to calculate the shadow tightly wraps your object. You can use the shadow.camera.near, shadow.camera.far, and shadow.camera.fov properties to configure this area.
Remember that you not only have to tell the light to cast shadows but also have to tell each geometry whether it will receive and/or cast shadows by setting the castShadow and receiveShadow properties.
Shadow bias
If you use thin objects in your scene, you might see strange artifacts when you render shadows. You can use the shadow.bias property to slightly offset the shadows, which will often fix these issues.
If you want to have softer shadows, you can set a different shadowMapType value on THREE.WebGLRenderer. By default, this property is set to THREE.PCFShadowMap; if you set this property to PCFSoftShadowMap, you’ll get softer shadows.
Now, let’s look at the next light source in the list: THREE.PointLight.
THREE.PointLight
Section titled “THREE.PointLight”THREE.PointLight is a light source that shines light in all directions emanating from a single point. A good example of a point light is a signal flare fired into the night sky or a campfire. Just as with all the lights, we have a specific example you can use to play around with THREE.PointLight. If you look at point-light.html in the chapter-03 folder, you can find an example where a THREE.PointLight is being used in the same scene we’re also using for the other lights:

Figure 3.13 – PointLight with the helper enabled
As you can see from the previous screenshot, this light emits to all sides. Just like the spotlight we saw earlier, this light also has a helper, which you can use in the same way. You can see this as the wireframe in the center of the scene:
const pointLightHelper = new THREE.PointLightHelper (pointLight);scene.add(pointLightHelper)// in the render looppointLightHelper.update();THREE.PointLight shares several properties with THREE.SpotLight, which you can use to configure how this light behaves:
| Name | Description |
|---|---|
color | The color of the light that this light source emits. |
distance | Indicates the distance for which the light shines. The default value is 0, which means that the light’s intensity doesn’t decrease based on distance. |
intensity | Indicates the intensity the light shines with. This defaults to 1. |
position | Indicates the position of the light in THREE.Scene. |
visible | Determines whether the light is turned off or on. If this property is set to true (the default), this light is turned on, and if set it to false, the light is turned off. |
decay | Indicates the amount the light intensity diminishes the farther you move away from the light source. A decay of 2 leads to more realistic light, and the default value is 1. This property is effective only when the physicallyCorrectLights property is set on WebGLRenderer. |
power | Refers to the light’s power when being rendered in the physically correct mode (enable this by setting the physicallyCorrectLights property set on WebGLRenderer). This property is measured in lumens and the default value is 4*Math.PI. Power is also directly related to the intensity property (power = intensity * 4π). |
Figure 3.14 – Properties of the THREE.PointLight object
Besides these properties, the THREE.PointLight object’s shadow can be configured in the same way as the shadow for THREE.SpotLight. In the next couple of examples and screenshots, we’ll show how these properties work for THREE.PointLight. First, let’s look at how you can create a THREE.PointLight:
const pointLight = new THREE.PointLight();scene.add(pointLight);There’s nothing special here – we just define the light and add it to the scene; you can, of course, set any of the properties we just showed as well. The two main properties of the THREE.SpotLight object are distance and intensity. With distance, you can specify how far the light is emitted before it decays to 0. For example, in the following screenshot, we set the distance property to a low value, and increased the intensity property a bit to simulate a campfire between the trees:

Figure 3.15 – PointLight with low distance and higher intensity
You can’t set the power and decay properties in this example; these properties are really useful if you want to simulate real-world scenarios. A good example of this can be found on the Three.js website: https://threejs.org/examples/#webgl_lights_physical.
THREE.PointLight also uses a camera to determine where to draw the shadows, so you can use THREE.CameraHelper to show what part is covered by that camera. In addition, THREE.PointLight provides a helper, THREE.PointLightHelper, to show where THREE.PointLight shines its light. With both enabled, you get the following very useful debug information:

Figure 3.16 – PointLight with helpers enabled
If you look closely at the previous screenshot (Figure 3*.16*), you might notice that shadows are created outside the area the shadow camera is showing. This is because the shadow helper only shows the shadows being cast down from the position of the point light. You can visualize a THREE.PointLight as a cube, where each side emits light and can cast shadows. In this case, THREE.ShadowCameraHelper only shows the shadows being cast down.
The last of the basic lights that we’ll be discussing is THREE.DirectionalLight.
THREE.DirectionalLight
Section titled “THREE.DirectionalLight”This type of light source can be considered as a light that is very far away. All the light rays it sends out are parallel to each other. A good example of this is the Sun. The Sun is so far away that the light rays we receive on Earth are (almost) parallel to each other. The main difference between THREE.DirectionalLight and THREE.SpotLight (which we saw previously) is that this light won’t diminish the farther it gets from the source as it does with THREE.SpotLight (you can fine-tune this with the distance and exponent parameters). The complete area that is lit by THREE.DirectionalLight receives the same intensity of light. To see this in action, look at the following directional-light.html example:

Figure 3.17 – Directional light simulating a sunset
As you can see, it is very easy to simulate, for instance, a sunset, using a THREE.DirectionalLight. Just as with THREE.SpotLight, there are a couple of properties you can set on this light. For example, you can set the intensity property of the light and the way it casts shadows. THREE.DirectionalLight has a lot of properties that are the same as those of THREE.SpotLight: position, target, intensity, castShadow, shadow.camera.near, shadow.camera.far, shadow.mapSize.width, shadow.mapSize.width, and shadowBias. For more information on those properties, you can look at the preceding section on THREE.SpotLight.
If you look back at the THREE.SpotLight examples, you will see that we had to define the cone of light where shadows were applied. Since all the rays are parallel to each other for THREE.DirectionalLight, we don’t have a cone where shadows need to be applied; instead, we have a cuboid area (represented internally with a THREE.OrthographicCamera), as you can see in the following screenshot, where we enabled the shadow helper:

Figure 3.18 – Directional light showing a cuboid shadow area
Everything that falls within this cube can cast and receive shadows from the light. Just as for THREE.SpotLight, the tighter you define this area around the objects, the better your shadows will look. Define this cube using the following properties:
directionalLight.castShadow = true;directionalLight.shadow.camera.near = 2;directionalLight.shadow.camera.far = 80;directionalLight.shadow.camera.left = -30;directionalLight.shadow.camera.right = 30;directionalLight.shadow.camera.top = 30;directionalLight.shadow.camera.bottom = -30;You can compare this with the way we configured the orthographic camera in the Using different cameras for different scenes section in Chapter 2.
As we’ve already seen in this section, light sources use colors. For now, we’ve just configured the colors using a hex string, but the THREE.Color object provides a lot of different options for creating the initial color object. In this next section, we’ll explore the functionality provided by the THREE.Color object.
Using the THREE.Color object
Section titled “Using the THREE.Color object”In Three.js, when you need to provide a color (for example, for materials, lights, and so on), you can pass in a THREE.Color object; otherwise, Three.js will create one from a passed-in string value, as we saw for THREE.AmbientLight. Three.js is very flexible when parsing the input for the THREE.Color constructor. You can create a THREE.Color object in the following ways:
- Hex string:
new THREE.Color("#ababab")will create a color based on the passed-in CSS color string. - Hex value:
new THREE.Color(0xababab)will create the color based on the passed-in hex value. If you know the hex value, this is usually the best approach. - RGB string:
new THREE.Color("rgb(255, 0, 0)")ornew THREE.Color("rgb(100%, ``0%, 0%)". - Color name: You can use named colors as well – for example,
new THREE.Color( 'skyblue' ). - HSL string: If you like working in the HSL domain instead of the RGB domain, you can pass in the HSL values with
new THREE.Color("hsl(0, ``100%, 50%)"). - Separate RGB values: You can specify the individual RGB components on a scale from 0 to 1:
new THREE.Color( 1, 0, ``0 ).
If you want to change the color after construction, you’ll have to create a new THREE.Color object or modify the internal properties of the THREE.Color object. The THREE.Color object comes with a large set of properties and functions. The first group of functions allows you to set the color of a THREE.Color object:
set(value): Sets the value of a color to the supplied hex value. This hex value may be a string, a number, or an existingTHREE.Colorinstance.setHex(value): Sets the value of a color to the supplied numeric hex value.setRGB(r,g,b): Sets the value of a color based on the supplied RGB values. The values range from0to1.setHSL(h,s,l): Sets the value of this color on the supplied HSL values. The values range from 0 to 1. A good explanation of how HSL works for configuring colors can be found at http://en.wikibooks.org/wiki/Color_Models:_RGB,_HSV,_HSL.setStyle(style): Sets the value of a color based on the CSS way of specifying colors. For instance, you could usergb(255,0,0),#ff0000,#f00, or evenred.
If you’ve already got an existing THREE.Color instance and want to use that color, you can use the following functions:
copy(color): Copies the color values from theTHREE.Colorinstance provided to this color.copySRGBToLinear(color): Sets the color of this object based on theTHREE.Colorinstance supplied. The color is first converted from the sRGB color space into the linear color space. The sRGB color space uses an exponential scale instead of a linear one. More information on the sRGB color space can be found here: https://www.w3.org/Graphics/Color/sRGB.html.copyLinearToSRGB(color): Sets the color of this object based on theTHREE.Colorinstance supplied. The color is first converted from the linear color space into the sRGB color space.convertSGRBToLinear(): Converts the current color from the sRGB color space into the linear color space.convertLinearToSGRB(): Converts the current color from the linear color space into the sRGB color space.
If you want information on the currently configured color, the THREE.Color object also provides some helper functions for that:
getHex(): Returns the value from this color object as a number:435241.getHexString(): Returns the value from this color object as a hex string:0c0c0c.getStyle(): Returns the value from this color object as a CSS-based value:rgb(112,0,0).getHSL(target): Returns the value from this color object as an HSL value ({ h: 0, s: 0, l: 0 }). If you provide the optionaltargetobject, Three.js will set theh,s, andlproperties on that object.
Three.js also provides functions to change the current color by modifying the individual color components. This is shown here:
offsetHSL(h, s, l): Adds theh,s, andlvalues provided to theh,s, andlvalues of the current color.add(color): Adds ther,g, andbvalues of the color supplied to the current color.addColors(color1, color2): Addscolor1andcolor2and sets the value of the current color to the result.addScalar(s): Adds a value to the RGB components of the current color. Bear in mind that the internal values use a range from0to1.multiply(color): Multiplies the current RGB values with the RGB values fromTHREE.Color.multiplyScalar(s): Multiplies the current RGB values with the value supplied. Remember that the internal values range between0to1.lerp(color, alpha): Finds the color that is between the color of this object and thecolorproperty supplied. Thealphaproperty defines how far between the current color and the supplied color you want the result to be.
Finally, there are a couple of basic helper methods available:
equals(color): Returnstrueif the RGB values of theTHREE.Colorinstance supplied match the values of the current colorfromArray(array): Has the same functionality assetRGB, but now, the RGB values can be provided as an array of numberstoArray: Returns an array with three elements:[r, ``g, b]clone: Creates an exact copy of a color
In the preceding lists, you can see that there are many ways in which you can change the current color. A lot of these functions are used internally by Three.js, but they also provide a good way to easily change the color of lights and materials, without having to create and assign new THREE.Color objects.
So far, we’ve looked at the basic lights provided by Three.js and how shadows work. In most cases, you’ll use a combination of these lights for your scene. Three.js also provides a couple of special lights for very specific use cases. We’ll look at those in the next section.
Working with special lights
Section titled “Working with special lights”In this section on special lights, we’ll discuss three additional lights provided by Three.js. First, we’ll discuss THREE.HemisphereLight, which helps in creating more natural lighting for outdoor scenes. Then, we’ll look at THREE.RectAreaLight, which emits lights from a large area instead of a single point. Next, we’ll look at how we can use a LightProbe to apply light based on a cubemap, and finally, we’ll show you how you can add a lens flare effect to your scene.
The first special light we’re going to look at is THREE.HemisphereLight.
THREE.HemisphereLight
Section titled “THREE.HemisphereLight”With THREE.HemisphereLight, we can create more natural-looking outdoor lighting. Without this light, we could simulate the outdoors by creating THREE.DirectionalLight, which emulates the sun, and maybe add another THREE.AmbientLight to provide some general color to the scene. However, doing so won’t look natural. When you’re outdoors, not all the light comes directly from above: much is diffused by the atmosphere and reflected by the ground and other objects. THREE.HemisphereLight in Three.js was created for this scenario. This is an easy way to get more natural-looking outdoor lighting. To see an example, look at hemisphere-light.html in the following figure:

Figure 3.19 – Hemisphere light
If you look closely at this screenshot, you will see that the ground color of the hemisphere is shown more at the bottom of the sphere, and the sky color (set through the color property) is visible at the top of the scene. In this example, you can set these colors and their intensity. Creating a hemisphere light is just as easy as creating any of the other lights:
const hemiLight = new THREE.HemisphereLight(0x0000ff, 0x00ff00, 0.6); hemiLight.position.set(0, 500, 0);scene.add(hemiLight);You just specify the color that is received from the sky, the color received from the ground, and the intensity of these lights. If you want to change these values later on, you can access them through the following properties:
| Property | Description |
|---|---|
groundColor | Indicates the color that is emitted from the ground |
color | Implies the color that is emitted from the sky |
intensity | Implies the intensity with which the light shines |
Figure 3.20 – Properties of the THREE.HemisphereLight object
Since a HemisphereLight acts like a THREE.AmbientLight object and just adds color to all the objects in the scene, it isn’t capable of casting shadows. The lights we’ve seen so far are more traditional. The next property allows you to simulate light from rectangular light sources – for instance, a window or a computer screen.
THREE.RectAreaLight
Section titled “THREE.RectAreaLight”With THREE.RectAreaLight, we can define a rectangular area that emits light. Before we look at the details, let’s first look at the result we’re aiming for (rectarea-light.html opens this example); the following screenshot shows a couple of THREE.RectAreaLight objects:

Figure 3.21 – RectArea lights emitting across their complete surface
What you see in this screenshot is that we’ve defined three THREE.RectAreaLight objects, each with its own color. You can see how these lights affect the whole area, and when you move them around or change their position, you can see how the different objects in the scene are affected.
We haven’t explored the different materials and how light affects them. We’ll do this in the next chapter, Chapter 4, Working with Three.js Materials. A THREE.RectAreaLight only works with THREE.MeshStandardMaterial or THREE.MeshPhysicalMaterial. More on these materials will be presented in Chapter 4.
To work with a THREE.RectAreaLight, we need to take a couple of small additional steps. First, we need to load and initialize RectAreaLightUniformsLib; the following is a set of additional low-level WebGL scripts needed by this light:
import { RectAreaLightUniformsLib } from "three/examples /jsm/lights/RectAreaLightUniformsLib.js";...RectAreaLightUniformsLib.init();Next, we can create the THREE.AreaLight object just like any other light:
const rectLight1 = new THREE.RectAreaLight (0xff0000, 5, 2, 5);rectLight1.position.set(-3, 0, 5);scene.add(rectLight1);If you look at the constructor of this object, you will see that it takes four properties. The first one is the color of the light, the second one is the intensity, and the last two define how large the area of this light is. Note that if you want to visualize these lights, as we did in the example, you have to create a rectangle yourself at the same position, rotation, and size as your THREE.RectAreaLight.
This light can be used to create some nice effects, but it’ll probably take some experimenting to get the effect you want. Once again, in this example, you’ve got a menu on the right-hand side that you can use to play around with the various settings.
In recent versions of Three.js, a new light was added called THREE.LightProbe. This light is similar to THREE.AmbientLight but takes the cubemap of WebGLRenderer into account. This is the last light source that we’ll discuss in this chapter.
THREE.LightProbe
Section titled “THREE.LightProbe”In the previous chapter, we talked a little bit about what a cubemap is. With a cubemap, you can show your models inside an environment. In the previous chapter, we used a cubemap to create a background that rotates with the view of the camera:

Figure 3.22 – Cubemap example from Chapter 2
As we’ll see in the next chapter, we can use the information from a cubemap to show reflections on our materials. Normally, though, these environment maps don’t contribute any light to your scene. With a THREE.LightProbe, however, we can extract lighting level information from the cubemap and use it to illuminate our models. So, what you’ll get looks a bit like a THREE.AmbientLight, but it affects the objects based on their location in the scene and the information from the cubemap.
The easiest way to explain this is by looking at an example. Open up light-probe.html in your browser; you’ll see the following scene:

Figure 3.23 – LightProbe with a model in a cave
In the preceding example, we’ve got a model inside a cave-like environment. What you can see, if you rotate the camera around, is that based on the light of the environment, our model is slightly differently lit. In the previous screenshot, we’re looking at the back of the object, which is further down in the cave, so the model is darker on that side. If we completely rotate the camera and set the entrance of the cave to our back, we’ll see that the model is much brighter and receives more light:

Figure 3.24 – LightProbe with a model in a cave receiving more light
This is a really neat trick to make your objects look more life-like and less flat, and with a THREE.LightProbe, your model will receive light non-uniformly, which looks much better.
Setting up a THREE.LightProbe is a bit more work but only needs to be done once when you create your scene. So long as you don’t change the environment, you don’t need to recalculate the values of the THREE.LightProbe object:
Import { LightProbeGenerator } from "three/examples/ jsm/lights//LightProbeGenerator";...const loadCubeMap = (renderer, scene) => { const base = "drachenfels"; const ext = "png"; const urls = [ "/assets/panorama/" + base + "/posx." + ext, "/assets/panorama/" + base + "/negx." + ext, "/assets/panorama/" + base + "/posy." + ext, "/assets/panorama/" + base + "/negy." + ext, "/assets/panorama/" + base + "/posz." + ext, "/assets/panorama/" + base + "/negz." + ext, ]; new THREE.CubeTextureLoader().load(urls, function (cubeTexture) { cubeTexture.encoding = THREE.sRGBEncoding; scene.background = cubeTexture; const lp = LightProbeGenerator.fromCubeTexture (cubeTexture); lp.intensity = 15; scene.add(lp); });};In the preceding code fragment, we do two main things. First, we use THREE.CubeTextureLoader to load in a cubemap. As we’ll see in the next chapter, a cubemap consists of six images representing the six sides of a cube, which together will make up our environment. Once that has been loaded, we set this to the background of our scene (note that this isn’t needed for THREE.LightProbe to work).
Now that we’ve got this cubemap, we can generate a THREE.LightProbe from it. This is done by passing in cubeTexture to a LightProbeGenerator. The result is a THREE.LightProbe, which we add to our scene, just like any other light. Just like with a THREE.AmbientLight, you can control how much this light contributes to the lighting of your meshes by setting the intensity property.
Note
There is also another kind of LightProbe provided by Three.js: THREE.HemisphereLightProbe. This one works pretty much the same as a normal THREE.HemisphereLight, but uses a LightProbe internally.
The final object in this chapter isn’t a light source but plays a trick on the camera often seen in movies: THREE.LensFlare.
THREE.LensFlare
Section titled “THREE.LensFlare”You are probably already familiar with lens flares. For instance, they appear when you take a direct photograph of the Sun or another bright light source. In most cases, you want to avoid this, but for games and 3D-generated images, it provides a nice effect that makes scenes look a bit more realistic. Three.js also has support for lens flares and makes it very easy to add them to your scene. In this last section, we’re going to add a lens flare to a scene and create the output shown in the following screenshot; you can see this for yourself by opening lens-flare.html:

Figure 3.25 – A lens flare appears when you look into the light
We can create a lens flare by instantiating the LensFlare object and by adding LensFlareElement objects:
import { Lensflare, LensflareElement,} from "three/examples/jsm/objects/Lensflare";const textureLoader = new THREE.TextureLoader()const textureFlare0 = textureLoader.load ('/assets/textures/lens-flares/lensflare0.png')const textureFlare1 = textureLoader.load ('/assets/textures/lens-flares/lensflare3.png')const lensFlare = new LensFlare();lensFlare.addElement(new LensflareElement (textureFlare0, 512, 0));lensFlare.addElement(new LensflareElement (textureFlare1, 60, 0.6));lensFlare.addElement(new LensflareElement (textureFlare1, 70, 0.7));lensFlare.addElement(new LensflareElement (textureFlare1, 120, 0.9));lensFlare.addElement(new LensflareElement (textureFlare1, 70, 1.0));pointLight.add(lensFlare);The LensFlare element is just a container for our LensFlareElement objects, and LensFlareElement is the artifact you see when you look at the light source. Then, we add LensFlare to the light source, and we’re done. If you look at the code, you will see that we pass in several properties for each LensFlareElement. These properties determine what LensFlareElement looks like and where it is rendered on screen. To use this element, we can apply the following constructor arguments:
| Property | Description |
|---|---|
texture | A texture is an image that determines the shape of the flare. |
size | We can specify how large the flare should be. size denotes the size in pixels. If you specify -1, the size of the texture itself is used. |
distance | Indicates the distance from the light source (0) to the camera (1). Use this to position the lens flare in the right position. |
color | Denotes the color of the flare. |
Figure 3.26 – Properties of the THREE.LensFlareElement object
First, let’s look a bit closer at the first LensFlareElement:
const textureLoader = new THREE.TextureLoader();const textureFlare0 = textureLoader.load( "/assets/textures/lens-flares/lensflare0.png");lensFlare.addElement(new LensflareElement (textureFlare0, 512, 0));The first argument, texture, is an image that shows the shape and some basic coloring of the flare. We load this with a THREE.TextureLoader, where we simply add the location of texture:

Figure 3.27 – Lens flare used in the example
The second argument is the size of this flare. Since this is the flare we see at the light source itself, we’re going to make it quite big: 512 pixels in this case. Next, we need to set the distance property of this flare. What you set here is the relative distance between the source of the light and the center of the camera. If we set a distance of 0, the texture will be shown at the position of the light, and if we set it to 1, it will be shown at the position of the camera. In this case, we put it directly at the light source.
Now, if you look back at the position of the other LightFlareElement objects, you will see that we positioned them at intervals from 0 to 1, which results in the effect you see when you open up the lens-flare.html example:
const textureFlare1 = textureLoader.load( "/assets/textures/lens-flares/lensflare3.png");lensFlare.addElement(new LensflareElement (textureFlare1, 60, 0.6));lensFlare.addElement(new LensflareElement (textureFlare1, 70, 0.7));lensFlare.addElement(new LensflareElement (textureFlare1, 120, 0.9));lensFlare.addElement(new LensflareElement (textureFlare1, 70, 1.0));With that, we’ve discussed the various lighting options provided by Three.js.
Summary
Section titled “Summary”In this chapter, we covered a lot of information about the different kinds of lights that are available in Three.js. You learned that configuring lights, colors, and shadows is not an exact science. To get the correct result, you should experiment with the different settings and use a lil.GUI control to fine-tune your configuration. The different lights behave in different ways and, as we’ll see in Chapter 4, materials respond differently to lights as well.
A THREE.AmbientLight color is added to every color in the scene and is often used to smooth hard colors and shadows. THREE.PointLight emits light in all directions and can cast shadows. THREE.SpotLight is a light that resembles a flashlight. It has a conical shape, can be configured to fade over distance, and can cast shadows. We also looked at THREE.DirectionalLight. This light can be compared to a faraway light, such as the Sun, whose light rays travel parallel to each other, the intensity of which doesn’t decrease the farther away it gets from the configured target, and which can also cast shadows.
Besides the standard lights, we also looked at a couple of more specialized lights. For a more natural outdoor effect, you can use THREE.HemisphereLight, which takes into account ground and sky reflections. THREE.RectAreaLight doesn’t shine from a single point but emits light from a large area. We also showed a more advanced sort of ambient lighting by using a THREE.LightProbe, which used information from an environment map to determine how an object is lit. Finally, we showed you how to add a photographic lens flare with the THREE.LenseFlare object.
In the chapters so far, we have already introduced a couple of different materials, and in this chapter, you saw that not all materials respond in the same manner to the available lights. In Chapter 4, we’ll provide an overview of the materials that are available in Three.js.