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.
To enable shadows in your Three.js scene, you need to configure three main components:
castShadow set to true, and objects that should receive shadows need to have receiveShadow set to true.renderer.shadowMap.enabled = true;
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:
light.shadow.mapSize.width and light.shadow.mapSize.height: Define the resolution of the shadow map. Higher values mean better quality but more performance cost.light.shadow.camera.near and light.shadow.camera.far: Define the frustum of the light's camera, similar to a regular camera.light.shadow.bias and light.shadow.normalBias: Small adjustments to help reduce shadow artifacts like "shadow acne."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
Three.js offers different shadow map types, which affect the quality and performance of shadows:
THREE.BasicShadowMap: Fastest, but lowest quality (hard edges).THREE.PCFShadowMap: (Default) Uses Percentage-Closer Filtering for smoother shadows.THREE.PCFSoftShadowMap: Provides even softer shadows with PCF.THREE.VSMShadowMap: Uses Variance Shadow Map algorithm.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
This example demonstrates a simple scene with a sphere casting a shadow onto a plane, illuminated by a DirectionalLight.