React Three Fiber (R3F) simplifies the process of incorporating lights, cameras, and materials into your 3D scenes by providing them as declarative React components. This allows you to define your scene's visual properties using familiar React syntax.
Lights are crucial for illuminating your 3D scene. R3F supports various types of lights, mirroring those available in Three.js. You can add lights as JSX components directly within your <Canvas> element.
<ambientLight />: Illuminates all objects in the scene equally, providing a general, diffused illumination.<pointLight />: Emits light from a single point in all directions, similar to a lamp.<directionalLight />: Simulates distant light sources like the sun, emitting parallel rays that illuminate the entire scene from a specific direction.<spotLight />: Emits light in a cone shape, useful for highlighting specific areas.import { Canvas } from '@react-three/fiber';
function SceneWithLights() {
return (
<Canvas>
<ambientLight intensity={0.5} />
<pointLight position={[10, 10, 10]} />
<directionalLight position={[-5, 5, 5]} />
<spotLight position={[0, 5, 0]} angle={0.3} penumbra={1} />
<!-- Your 3D objects go here -->
</Canvas>
);
}
The camera defines what is visible in your 3D scene and how it is viewed. By default, R3F's <Canvas> component sets up a THREE.PerspectiveCamera. You can customize the camera's properties directly on the <Canvas> component or by adding a dedicated camera component.
fov (Field of View): Determines the vertical angle the camera can see.aspect (Aspect Ratio): The width-to-height proportion of the camera's view.near and far: Define the clipping planes; objects outside this range are not rendered.position: The camera's location in 3D space.import { Canvas } from '@react-three/fiber';
function SceneWithCustomCamera() {
return (
<Canvas camera={{ fov: 75, position: [0, 0, 5] }}>
<!-- Your 3D objects go here -->
</Canvas>
);
}
Materials define the visual properties of your 3D objects, such as color, shininess, and how they react to light. R3F allows you to apply various Three.js materials to your meshes as child components.
<meshBasicMaterial />: A simple material not affected by lights.<meshLambertMaterial />: Reacts to light, suitable for non-shiny surfaces.<meshPhongMaterial />: Reacts to light, supports specular highlights for shiny surfaces.<meshStandardMaterial />: A physically-based rendering (PBR) material that offers realistic lighting interactions with properties like metalness and roughness. Often preferred for realistic scenes.import { Canvas } from '@react-three/fiber';
function SceneWithMaterials() {
return (
<Canvas>
<ambientLight />
<pointLight position={[10, 10, 10]} />
<mesh>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color="hotpink" roughness={0.5} metalness={0.1} />
</mesh>
</Canvas>
);
}