⚡️ Limited Black Friday Deal
Get 50% off on the React Three Fiber Ultimate Course with the promo code ULTIMATE50
Buy Now
Fundamentals
Core
Master
Shaders
Shadows
In 3D graphics, shadows are used to simulate the effect of light hitting an object and casting a shadow on another object.
Cast and receive shadows
React Three Fiber makes it easy to add shadows to a scene.
The first thing we need to do is to enable shadows globally by adding the shadows
props on the <Canvas />
component:
<Canvas shadows />
Then, you need to enable shadows on the objects that will cast shadows:
<mesh castShadow />
And on the objects that will receive shadows:
<mesh receiveShadow />
Of course, you can enable both on the same object:
<mesh castShadow receiveShadow />
Let's do it on our project:
<Canvas shadows camera={{ position: [0, 3, 3] }}> {/* ... */} <mesh rotation-y={Math.PI / 4} castShadow> <boxGeometry /> <meshStandardMaterial color="white" /> </mesh> <mesh rotation-x={-Math.PI / 2} position-y={-0.5} receiveShadow> <planeGeometry args={[5, 5]} /> <meshStandardMaterial color="white" /> </mesh> </Canvas>
We added shadows
on the <Canvas />
, castShadow
on the cube and receiveShadow
on the plane but nothing happens.
This is because we also need to tell which light will cast shadows.
{ /* ... */ } <directionalLight position={[5, 5, 5]} intensity={0.5} castShadow />; { /* ... */ }
Now, we can see the shadow of the cube on the plane. We can also set shadows from multiple lights:
{/* ... */} <directionalLight position={[5, 5, 5]} intensity={0.5} castShadow /> <directionalLight position={[-5, 5, 5]} intensity={0.5} color="red" castShadow /> {/* ... */}
See how the shadow color is impacted by the color of the lights.
Let's add a sphere to the scene:
End of lesson preview
To get access to the entire lesson, you need to purchase the course.