Three.js Light Guide: Intensity, Color, and Decay
Controlling lighting is crucial for creating realistic 3D scenes in Three.js. This article provides a straightforward guide on how to manipulate the intensity, color, and decay properties of light sources in Three.js, helping you achieve the perfect atmosphere and visual realism in your web-based 3D projects.
Initializing a Light Source
To manipulate light properties, you first need to create a light
source. While properties like color and intensity apply to almost all
lights, decay is specific to lights that cast in a limited range, such
as PointLight and SpotLight.
Here is how to set up a basic PointLight:
import * as THREE from 'three';
// Syntax: PointLight(color, intensity, distance, decay)
const light = new THREE.PointLight(0xffffff, 1, 100, 2);
scene.add(light);Controlling Light Color
The color of a light source determines the hue of the light it emits.
In Three.js, light color is stored as a THREE.Color object,
which can be modified dynamically after instantiation.
You can change the color using hexadecimal values, color names, or RGB values:
// Method 1: Using a hexadecimal hex value
light.color.setHex(0xff5500);
// Method 2: Using a CSS color string
light.color.set('hotpink');
// Method 3: Using RGB values (normalized between 0 and 1)
light.color.setRGB(0.2, 0.8, 1.0);Controlling Light Intensity
The intensity property determines the brightness of the
light. The default value is typically 1, but you can
increase or decrease this value to match your scene’s requirements.
// Dim the light
light.intensity = 0.5;
// Make the light much brighter
light.intensity = 5.0;In modern versions of Three.js, physically correct lighting is
enabled by default. This means intensity is measured in Lumens or
Candelas, requiring higher intensity values (e.g., 100 or
1000 depending on the scene scale) to illuminate objects
realistically.
Controlling Light Decay
Decay describes how the light’s intensity dims as it moves further
away from the source. This property only applies to lights with a finite
range, such as PointLight and SpotLight.
To control decay, you must configure two properties: 1.
distance: The maximum range of the light.
If set to 0, the light shines infinitely. 2.
decay: The rate at which the light dims
over the distance.
// Set the maximum reach of the light to 50 units
light.distance = 50;
// Set the decay rate
light.decay = 2; Decay Value Guidelines:
0: The light does not decay at all; it maintains full intensity up to its maximum distance.1: Linear decay (useful for stylized or performance-friendly lighting).2: Physically realistic decay (conforms to the real-world inverse-square law). This is the recommended setting for realistic scenes.