Lesson 5 of 13

Shadows

Shadows

Shadows add realism by grounding objects in the scene. Three.js uses shadow maps — the renderer draws the scene from each light's perspective to determine what is in shadow.

Enabling Shadows

Shadows are off by default. You need to flip three switches:

  1. Renderer — enable the shadow map engine:
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // softer edges
  1. Light — tell the light to cast shadows:
const light = new THREE.DirectionalLight(0xffffff, 2);
light.castShadow = true;
  1. Objects — each mesh decides whether it casts and/or receives:
cube.castShadow = true;    // this object blocks light
floor.receiveShadow = true; // shadows appear on this surface

Shadow Map Types

Three.js provides several shadow map algorithms:

TypeQualityPerformance
THREE.BasicShadowMapHard edges, blockyFastest
THREE.PCFShadowMapSmoother edges (default)Medium
THREE.PCFSoftShadowMapSoft, natural lookSlower
THREE.VSMShadowMapVery soft, some artifactsSlower

Shadow Camera

Each shadow-casting light has a shadow.camera that controls the shadow frustum. For DirectionalLight, it is an orthographic camera:

light.shadow.camera.top = 10;
light.shadow.camera.bottom = -10;
light.shadow.camera.left = -10;
light.shadow.camera.right = 10;
light.shadow.camera.near = 0.5;
light.shadow.camera.far = 50;

Shadow Map Size

Higher resolution = sharper shadows but more GPU memory:

light.shadow.mapSize.width = 2048;
light.shadow.mapSize.height = 2048;

Which Lights Cast Shadows?

Only DirectionalLight, PointLight, and SpotLight can cast shadows. AmbientLight and HemisphereLight cannot.

Your Task

Implement setupShadows(renderer, light, caster, receiver) that:

  • Enables the shadow map on renderer with PCFSoftShadowMap type
  • Sets light.castShadow to true
  • Sets shadow map size to 2048 x 2048 on the light
  • Sets caster.castShadow to true
  • Sets receiver.receiveShadow to true
Three.js loading...
Loading...
Click "Run" to execute your code.