Immersive 3D Experiences with Three.js
Build captivating 3D web experiences with Three.js and modern techniques.
Introduction
Three.js is the standard library for 3D graphics on the web. It abstracts away the complexities of WebGL, allowing you to create scenes, cameras, lights, and meshes with ease.
In this tutorial, we'll create an interactive 3D portfolio scene.
Setting Up the Scene
A basic Three.js scene requires three things: a scene, a camera, and a renderer.
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
Adding Objects
Let's add a spinning cube.
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
Lighting and Materials
MeshBasicMaterial doesn't react to light. Let's switch to MeshStandardMaterial and add some lights.
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
// ...
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const pointLight = new THREE.PointLight(0xffffff, 1);
pointLight.position.set(5, 5, 5);
scene.add(pointLight);
React Three Fiber (R3F)
If you are using React, react-three-fiber is a must. It allows you to write Three.js code declaratively as components.
import { Canvas } from '@react-three/fiber'
function Box(props) {
return (
<mesh {...props}>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial color={'orange'} />
</mesh>
)
}
export default function App() {
return (
<Canvas>
<ambientLight />
<pointLight position={[10, 10, 10]} />
<Box position={[-1.2, 0, 0]} />
<Box position={[1.2, 0, 0]} />
</Canvas>
)
}
Conclusion
Three.js opens up a world of possibilities for creative web development. From product configurators to games and data visualizations, the only limit is your imagination.