How to cast shadows in three.js
Three.js is a JavaScript library. It uses WebGL to render graphics on the web.
The shapes and animations rendered by default using three.js do not cast shadows. This Answer will explain how to enable shadows in our three.js scene.
Enable shadows
To make our scene use shadows, we need to follow the steps below:
First, we need to set the shadowMap property of the renderer to true.
// initialization
const renderer = new THREE.WebGLRenderer()
// setting type
renderer.shadowMap.enabled = true;
We can also set the type of the shadowMap that we want our renderer to use. Shadow maps use shadow projection techniques to cast shadows in the scene. By default, the renderer uses BasicShadowMap. This type gives the fastest shadows, but they are of the lowest quality.
Other than this, we also need to enable castShadow for our light source.
// initialization
const light = new THREE.DirectionalLight(color, intensity);
// enabling casting shadows
light.castShadow = true;
Here, the constructor for DirectionalLight takes the following parameters:
- The
colorof the light is in hexadecimal format. - The
intensityof the light, which is of typefloat.
The next step is to choose the objects that will cast shadows and those that will receive shadows. This is achieved by tampering with the castShadow and receiveShadow properties of the object.
// this object will cast and receive shadows
shape_one.castShadow = true;
shape_one.receiveShadow = true;
// this object will cast shadows but not receive them
shape_two.castShadow = true;
shape_two.receiveShadow = false;
Note: Only the lights that have a direction associated with them can cast shadows. Lights such as Ambient light and Hemisphere light do not cast shadows.
Code example
The example below illustrates the use of shadows in three.js:
Code explanation
In the code shown above, we first set up the scene. Other than that, the explanation of the code is given below:
Lines 33–34: We enable the
shadowMapproperty of therendererobject and set the type toBasicShadowMap.Line 40: We initialize
OrbitControls. This allows the user to pan around the scene and observe from different angles. To read more onOrbitControls, please follow this link.Lines 47–48: We set the
castShadowandreceiveShadowproperties of the plane totrueso that it casts and receives shadows.Line 61: We set the
castShadowproperty of thesphereobject so that it casts a shadow on the plane placed below.Line 68: We enable the
castShadowproperty of thelightobject to allow the casting of shadows on the objects that the light falls on.
Free Resources