Shadows and lighting logic

Back to Modules

Shadows and Lighting Logic in Three.js

Shadows add a crucial layer of realism to 3D scenes by providing depth cues and grounding objects within their environment. Three.js implements shadows using a technique called shadow mapping.

Enabling Shadows

To enable shadows in your Three.js scene, you need to configure three main components:

  1. Renderer: You must enable shadow maps on the WebGLRenderer.
  2. Light Source: Only certain light types can cast shadows. You need to explicitly enable shadow casting for these lights.
  3. Objects: Objects that should cast shadows need to have castShadow set to true, and objects that should receive shadows need to have receiveShadow set to true.

1. Enable Shadows on the Renderer

renderer.shadowMap.enabled = true;

2. Configure the Light Source

Only DirectionalLight, PointLight, and SpotLight can cast shadows. For your chosen light, set:

light.castShadow = true;

You can also adjust properties of the light's shadow camera to control the quality and extent of the shadows:

3. Configure Objects

For each Mesh object in your scene:

mesh.castShadow = true;   // If this object should cast a shadow
mesh.receiveShadow = true; // If this object should receive shadows

Shadow Map Types

Three.js offers different shadow map types, which affect the quality and performance of shadows:

renderer.shadowMap.type = THREE.PCFSoftShadowMap;

Example: Shadows in Action

This example demonstrates a simple scene with a sphere casting a shadow onto a plane, illuminated by a DirectionalLight.