Getting Started with Three.js
This guide is based on DISCOVER three.js with enhancements and additional insights for better understanding.
Table of Contents
- Understanding 3D Coordinate Systems
- Three.js Repository Structure
- Installation Methods
- Project Setup
- Core Concepts
- Best Practices
Understanding 3D Coordinate Systems
The Cartesian Coordinate System (3D)
Three.js uses a right-handed coordinate system based on Cartesian coordinates. Understanding this is fundamental to working with 3D graphics.
Key Characteristics:
- X-axis: Horizontal (left to right, positive to the right)
- Y-axis: Vertical (bottom to top, positive upward)
- Z-axis: Depth (back to front, positive toward the viewer)
Right-Hand Rule: To remember the coordinate system orientation, use your right hand:
- Point your thumb to the right (positive X)
- Point your index finger upward (positive Y)
- Point your middle finger toward yourself (positive Z)
// Example: Positioning objects in 3D space
mesh.position.set(
2, // X: 2 units to the right
3, // Y: 3 units up
-5 // Z: 5 units away from camera
);Important Notes:
- Different 3D software may use different coordinate systems (left-handed vs right-handed)
- When importing models from other software, you may need to adjust rotations or coordinate mappings
- Three.js cameras look down the negative Z-axis by default
Reference: Cartesian Coordinate System (Wikipedia)
Three.js Repository Structure
Understanding the GitHub repository structure helps you locate resources and understand the library organization.
Core Files: The build/ Folder
The build folder contains the most critical files:
build/three.module.js ⭐
This is the only file you need to run a basic three.js application.
- Modern ES6 module format
- Recommended for all new projects
- Tree-shakable (only imports what you use)
- Better for build tools and bundlers
Legacy Versions (Soon to be deprecated)
build/three.js: Classic script formatbuild/three.min.js: Minified classic format
Note: Legacy versions support older browsers but will be removed in future releases.
The examples/ Folder: Your Learning Goldmine
The examples/ folder is invaluable for learning:
📚 Learning Resources
Official Examples Source Code
- Browse all examples
- Study the source code
- Essential learning resource alongside documentation
Modern Plugins:
examples/jsm/- Camera controls
- Model loaders (GLTF, OBJ, FBX, etc.)
- Post-processing effects
- Utilities and helpers
Legacy Plugins:
examples/js/(Being phased out)- Same functionality as
jsm/but in old format - Only use if you must support very old browsers
- Same functionality as
🎨 Assets and Resources
All these resources are MIT licensed - free to use in your projects:
- 3D Fonts: JSON fonts for 3D text
- 3D Models: Various formats (GLTF, OBJ, FBX, etc.)
- Sound Effects: Audio for 3D audio visualization
- Textures: PBR materials, environment maps, etc.
Pro Tip: The examples folder is your best teacher. Study the code, experiment with examples, and learn patterns from real implementations.
Installation Methods
Method 1: NPM/Yarn (Recommended) 📦
Advantages:
- Version control and dependency management
- Works with modern build tools (Webpack, Vite, Parcel)
- Tree-shaking for smaller bundle sizes
- Easy updates
# Initialize NPM project
npm init -y
# Install three.js
npm install three
# Or using Yarn
yarn add threeMethod 2: CDN (Quick Prototyping) ⚡
Advantages:
- No build process required
- Perfect for quick experiments
- No installation needed
<!DOCTYPE html>
<html>
<head>
<title>Three.js CDN Example</title>
</head>
<body>
<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js';
// Your three.js code here
const scene = new THREE.Scene();
// ...
</script>
</body>
</html>Popular CDNs:
- jsDelivr:
https://cdn.jsdelivr.net/npm/three@<version>/build/three.module.js - unpkg:
https://unpkg.com/three@<version>/build/three.module.js
Method 3: Local Download
Download from threejs.org and reference locally.
Project Setup
Basic Import Patterns
Core Classes
// Import specific classes (recommended for tree-shaking)
import {
Scene,
PerspectiveCamera,
WebGLRenderer,
BoxGeometry,
MeshBasicMaterial,
Mesh,
DirectionalLight
} from 'three';Importing the Entire Library
// Import everything as THREE namespace
import * as THREE from 'three';
// Then use with THREE prefix
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);Importing Add-ons and Plugins
Important: Add-ons use a different import path!
// Camera controls
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// Model loaders
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
// Post-processing
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
// Utilities
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';Note: The path structure is: three/examples/jsm/<category>/<ClassName>.js
Core Concepts
The Three.js Rendering Pipeline
Every three.js application needs these three fundamental components:
// 1. Scene - The container for all 3D objects
const scene = new Scene();
// 2. Camera - Your viewpoint into the 3D world
const camera = new PerspectiveCamera(
75, // Field of view in degrees
window.innerWidth / window.innerHeight, // Aspect ratio
0.1, // Near clipping plane
1000 // Far clipping plane
);
// 3. Renderer - Draws the scene from camera's perspective
const renderer = new WebGLRenderer({
antialias: true // Smooth edges
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Render the scene
renderer.render(scene, camera);Essential Components
Geometries
Define the shape of 3D objects:
const geometry = new BoxGeometry(1, 1, 1); // width, height, depth
const sphereGeometry = new SphereGeometry(1, 32, 32); // radius, width segments, height segmentsMaterials
Define how objects appear:
const material = new MeshBasicMaterial({ color: 0x00ff00 }); // Simple, unlit
const phongMaterial = new MeshPhongMaterial({ color: 0x00ff00 }); // Shiny, requires lights
const standardMaterial = new MeshStandardMaterial({ // PBR material
color: 0x00ff00,
metalness: 0.5,
roughness: 0.5
});Meshes
Combine geometry + material:
const mesh = new Mesh(geometry, material);
scene.add(mesh);Lights
Illuminate the scene:
const ambientLight = new AmbientLight(0xffffff, 0.5); // Soft overall light
const directionalLight = new DirectionalLight(0xffffff, 1); // Sun-like light
directionalLight.position.set(5, 5, 5);
scene.add(ambientLight, directionalLight);Best Practices
1. Use Modern ES6 Modules
// ✅ Good
import { Scene, Mesh } from 'three';
// ❌ Avoid (legacy)
<script src="three.js"></script>2. Always Dispose Resources
// Prevent memory leaks
geometry.dispose();
material.dispose();
texture.dispose();
renderer.dispose();3. Responsive Design
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});4. Animation Loop
function animate() {
requestAnimationFrame(animate);
// Update logic here
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();5. Optimize Performance
- Reuse geometries and materials when possible
- Use
BufferGeometryinstead ofGeometry(deprecated) - Implement frustum culling
- Use LOD (Level of Detail) for complex scenes
- Minimize draw calls by merging geometries
6. Development Tools
// Add helpers during development
import { GridHelper, AxesHelper } from 'three';
const gridHelper = new GridHelper(10, 10);
const axesHelper = new AxesHelper(5);
scene.add(gridHelper, axesHelper);Quick Start Template
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
// Scene setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x222222);
// Camera setup
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 5;
// Renderer setup
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// Controls
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 5, 5);
scene.add(ambientLight, directionalLight);
// Create a simple cube
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Animation loop
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
controls.update();
renderer.render(scene, camera);
}
// Handle window resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Start animation
animate();Additional Resources
- Official Documentation: threejs.org/docs
- Examples: threejs.org/examples
- Discourse Forum: discourse.threejs.org
- GitHub Repository: github.com/mrdoob/three.js
- DISCOVER three.js: discoverthreejs.com
Next Steps:
- Experiment with the quick start template
- Modify geometries, materials, and positions
- Explore the official examples
- Try adding different lights and see how they affect your scene
- Learn about textures and advanced materials
Happy coding with Three.js! 🚀