Enable Shadow Mapping Globally in Three.js
This article provides a quick, step-by-step guide on how to globally
enable and configure shadow mapping within the Three.js
WebGLRenderer. You will learn how to activate the shadow
map setting on the renderer, choose a shadow map type for better visual
quality, and configure individual lights and meshes to cast and receive
shadows in your 3D scene.
To enable shadow mapping globally in Three.js, you must configure the
shadowMap property of your WebGLRenderer
instance. By default, shadows are disabled to optimize performance.
Step 1: Enable the Shadow Map on the Renderer
Instantiate your renderer and set the shadowMap.enabled
property to true.
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Enable shadow maps globally
renderer.shadowMap.enabled = true;Step 2: Choose a Shadow Map Type
You can define the shadow filtering algorithm by setting
renderer.shadowMap.type. While
THREE.PCFShadowMap is the default,
THREE.PCFSoftShadowMap is commonly used for smoother, less
pixelated shadow edges.
// Set shadow map type for softer shadows
renderer.shadowMap.type = THREE.PCFSoftShadowMap; The available types are: * THREE.BasicShadowMap:
Unfiltered shadow maps (fastest, but pixelated). *
THREE.PCFShadowMap: Percentage-Closer Filtering (default).
* THREE.PCFSoftShadowMap: Softer PCF shadows (recommended
for realism). * THREE.VSMShadowMap: Variance Shadow Map
(high quality, different performance characteristics).
Step 3: Configure Lights to Cast Shadows
Enabling shadows globally on the renderer prepares the system, but you must still specify which lights cast shadows. Directional, Point, and Spot lights support shadows.
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 10, 7);
// Enable shadow casting for this light
light.castShadow = true;
scene.add(light);Step 4: Configure Meshes to Cast and Receive Shadows
Finally, define which 3D objects in your scene cast shadows and which surfaces receive them.
// Create a mesh that casts a shadow
const sphereGeometry = new THREE.SphereGeometry(1, 32, 32);
const sphereMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
sphere.castShadow = true; // Active shadow casting
scene.add(sphere);
// Create a floor plane that receives the shadow
const floorGeometry = new THREE.PlaneGeometry(10, 10);
const floorMaterial = new THREE.MeshStandardMaterial({ color: 0xcccccc });
const floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true; // Active shadow receiving
scene.add(floor);