Three.js Basics
Render your first 3D scene in the browser with zero dependencies beyond the library itself.
1. Scene, Camera, Renderer
Every Three.js project starts with three core objects. The Scene holds all your meshes and lights. The PerspectiveCamera defines the viewport, and the WebGLRenderer draws everything to a canvas.
2. Adding Geometry
Create a BoxGeometry and wrap it with aMeshStandardMaterial. Combine them into aMesh and add it to the scene. Without lights, the mesh renders black — add an AmbientLight and aDirectionalLight.
3. Animation Loop
Use requestAnimationFrame to create a render loop. Rotate the mesh on each frame by incrementing mesh.rotation.y. Call renderer.render(scene, camera) inside the loop.
4. Responsive Canvas
Listen for window.resize events. Update the camera aspect ratio and renderer size so your scene looks sharp on every screen.
Pro tip: Install Three.js via npm and import it as an ES module. Avoid CDN script tags — tree-shaking keeps your bundle lean.