Three.js Contact Shadows (Soft Grounding Shadows)

Soft contact shadows in Three.js, rendered from below the floor with an orthographic camera, converted from depth to darkness, blurred with separable passes and projected onto a ground plane, compared with directional shadow maps.

Key topics: three.js contact shadows, soft shadows, ground shadow, blur, product viewer, shadow plane

What this code does

- Capture: an orthographic camera under the floor looks up and renders the scene with a depth material.
- Height → Darkness: the depth shader is rewritten so fragments closer to the floor are darker and more opaque.
- Blur: horizontal then vertical Gaussian passes, run twice, give a soft penumbra that widens with height.
- Projection: the blurred texture sits on a transparent plane under the objects, flipped because it was captured from below.
- Why Use It: grounding shadows don't depend on a light direction, which makes them ideal for product viewers.
- Comparison: switch to a regular shadow map, or combine both.
- Controls: shadow mode, blur, darkness, opacity and bouncing objects.

Continue Learning

JavaScript Implementation

ES6+
// Contact shadows: render depth from under the floor, darken by height, blur, project onto a plane
const rt = new THREE.WebGLRenderTarget(512, 512)
const shadowCam = new THREE.OrthographicCamera(-4, 4, 4, -4, 0, 2.5)
shadowCam.rotation.x = Math.PI / 2 // look up at the objects from the ground
const depthMat = new THREE.MeshDepthMaterial()
depthMat.onBeforeCompile = (shader) => {
  shader.fragmentShader = shader.fragmentShader.replace(
    'gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );',
    'gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * 1.2 );')
}
scene.overrideMaterial = depthMat
renderer.setRenderTarget(rt); renderer.render(scene, shadowCam)
scene.overrideMaterial = null
// …blur rt with HorizontalBlurShader / VerticalBlurShader, then:
const plane = new THREE.Mesh(new THREE.PlaneGeometry(8, 8).rotateX(Math.PI / 2), new THREE.MeshBasicMaterial({ map: rt.texture, transparent: true }))
plane.scale.y = -1