Creating a 3D scene in Three.js involves setting up a renderer, a scene, and a camera. These are the absolute minimum requirements to display anything in 3D on your web page.
The renderer is responsible for taking your 3D scene and displaying it on a 2D canvas. The most common renderer is `WebGLRenderer`, which uses the WebGL API for hardware-accelerated 3D graphics.
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
The scene is where you place all your 3D objects, lights, and cameras. Think of it as a container or a stage for your 3D world.
const scene = new THREE.Scene();
The camera defines what the user sees in your 3D scene. There are different types of cameras, but `PerspectiveCamera` is the most common for simulating human vision.
const camera = new THREE.PerspectiveCamera(
75, // Field of view
window.innerWidth / window.innerHeight, // Aspect ratio
0.1, // Near clipping plane
1000 // Far clipping plane
);
camera.position.z = 5; // Move camera back to see objects
To make your scene interactive and dynamic, you need a render loop. This function is called repeatedly (typically 60 times per second) to update the scene and redraw the frame.
function animate() {
requestAnimationFrame(animate);
// Update objects here (e.g., cube.rotation.x += 0.01;)
renderer.render(scene, camera);
}
animate();
Imagine you want to display a 3D model of a product on a webpage. By setting up a basic Three.js scene, you can load your product model, add some lighting to make it visible, and position a camera to give the user a good view. The render loop would then allow for simple animations or user interactions like rotating the product.