Three.
js Complete Documentation Guide
Table of Contents
1. Introduction
2. Getting Started
3. Core Concepts
4. Basic Scene Setup
5. Geometries
6. Materials
7. Lights
8. Cameras
9. Controls
10. Textures
11. Animation
12. Loading Models
13. Helpers and Debug Tools
14. Performance Optimization
15. Common Patterns
16. Troubleshooting
Introduction
[Link] is a powerful JavaScript library that makes creating 3D graphics in web browsers accessible and
straightforward. Built on top of WebGL, [Link] abstracts the complexity of low-level graphics
programming while providing extensive capabilities for creating interactive 3D experiences.
Key Features
WebGL Abstraction: Simplifies WebGL programming
Cross-platform: Works across modern browsers
Rich Ecosystem: Extensive collection of geometries, materials, and effects
Active Community: Large community with extensive documentation
Flexible Architecture: Modular design allowing selective imports
Use Cases
Data visualization
Games and interactive experiences
Product configurators
Architectural visualizations
Educational simulations
Art and creative coding
Getting Started
Installation
Via CDN
html
<script src="[Link]
Via npm
bash
npm install three
ES6 Import
javascript
import * as THREE from 'three';
Basic HTML Setup
html
<!DOCTYPE html>
<html>
<head>
<title>[Link] Scene</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<script src="[Link]
<script>
// Your [Link] code here
</script>
</body>
</html>
Core Concepts
The [Link] Trinity
Every [Link] application requires three fundamental components:
1. Scene: Container for all 3D objects
2. Camera: Defines the viewpoint
3. Renderer: Draws the scene to the screen
Object Hierarchy
[Link] uses a scene graph structure where objects can have children, creating hierarchical relationships
that affect transformations.
Coordinate System
[Link] uses a right-handed coordinate system:
X-axis: Left (-) to Right (+)
Y-axis: Down (-) to Up (+)
Z-axis: Into screen (-) to Out of screen (+)
Basic Scene Setup
Minimal Scene Example
javascript
// Create scene
const scene = new [Link]();
// Create camera
const camera = new [Link](
75, // Field of view
[Link] / [Link], // Aspect ratio
0.1, // Near clipping plane
1000 // Far clipping plane
);
// Create renderer
const renderer = new [Link]();
[Link]([Link], [Link]);
[Link]([Link]);
// Create a cube
const geometry = new [Link](1, 1, 1);
const material = new [Link]({ color: 0x00ff00 });
const cube = new [Link](geometry, material);
[Link](cube);
// Position camera
[Link].z = 5;
// Render the scene
[Link](scene, camera);
Animation Loop
javascript
function animate() {
requestAnimationFrame(animate);
// Rotate the cube
[Link].x += 0.01;
[Link].y += 0.01;
[Link](scene, camera);
}
animate();
Responsive Design
javascript
function onWindowResize() {
[Link] = [Link] / [Link];
[Link]();
[Link]([Link], [Link]);
}
[Link]('resize', onWindowResize);
Geometries
Geometries define the shape and structure of 3D objects.
Built-in Geometries
BoxGeometry
javascript
const geometry = new [Link](width, height, depth);
// Optional: segments for smoother surfaces
const detailedBox = new [Link](1, 1, 1, 2, 2, 2);
SphereGeometry
javascript
const geometry = new [Link](
radius, // Radius
widthSegments, // Horizontal segments
heightSegments // Vertical segments
);
PlaneGeometry
javascript
const geometry = new [Link](width, height, widthSegments, heightSegments);
CylinderGeometry
javascript
const geometry = new [Link](
radiusTop, // Top radius
radiusBottom, // Bottom radius
height, // Height
radialSegments // Radial segments
);
Common Geometries Quick Reference
ConeGeometry : Cone shapes
TorusGeometry : Donut shapes
RingGeometry : Flat rings
CircleGeometry : Flat circles
OctahedronGeometry : Eight-sided polyhedron
IcosahedronGeometry : Twenty-sided polyhedron
Custom Geometries
javascript
const geometry = new [Link]();
const vertices = new Float32Array([
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0
]);
[Link]('position', new [Link](vertices, 3));
Geometry Methods
javascript
[Link](); // Center geometry at origin
[Link](x, y, z); // Scale geometry
[Link](angle); // Rotate around X axis
[Link](x, y, z); // Move geometry
[Link](); // Calculate bounding box
Materials
Materials define how surfaces respond to light and appear visually.
Basic Materials
MeshBasicMaterial
javascript
const material = new [Link]({
color: 0xff0000, // Red color
wireframe: true, // Show wireframe
transparent: true, // Enable transparency
opacity: 0.8 // 80% opacity
});
MeshStandardMaterial (PBR)
javascript
const material = new [Link]({
color: 0xffffff, // Base color
roughness: 0.5, // Surface roughness (0-1)
metalness: 0.1, // Metallic property (0-1)
emissive: 0x000000 // Emissive color
});
MeshPhongMaterial
javascript
const material = new [Link]({
color: 0xffffff, // Diffuse color
specular: 0x111111, // Specular color
shininess: 100 // Shininess factor
});
Material Properties
javascript
[Link] = [Link]; // Render both sides
[Link] = [Link]; // Render back only
[Link] = [Link]; // Render front only (default)
[Link] = true;
[Link] = 0.5;
[Link] = false; // Hide material
Material Types Quick Reference
MeshLambertMaterial : Simple diffuse shading
MeshToonMaterial : Cartoon-style shading
MeshNormalMaterial : Colors based on normal vectors
MeshDepthMaterial : Colors based on depth
PointsMaterial : For point clouds
LineBasicMaterial : For lines
LineDashedMaterial : For dashed lines
Lights
Lighting is crucial for realistic 3D scenes (except with MeshBasicMaterial).
Light Types
AmbientLight
javascript
const ambientLight = new [Link](0x404040, 0.5); // Soft white light
[Link](ambientLight);
DirectionalLight
javascript
const directionalLight = new [Link](0xffffff, 1);
[Link](5, 5, 5);
[Link](0, 0, 0);
[Link](directionalLight);
[Link]([Link]);
PointLight
javascript
const pointLight = new [Link](0xffffff, 1, 100);
[Link](10, 10, 10);
[Link](pointLight);
SpotLight
javascript
const spotLight = new [Link](0xffffff, 1);
[Link](100, 1000, 100);
[Link](0, 0, 0);
[Link] = [Link] / 4; // 45 degrees
[Link] = 0.1; // Soft edges
[Link](spotLight);
[Link]([Link]);
Shadow Configuration
javascript
// Enable shadows in renderer
[Link] = true;
[Link] = [Link];
// Configure light to cast shadows
[Link] = true;
[Link] = 2048;
[Link] = 2048;
// Configure objects to cast/receive shadows
[Link] = true;
[Link] = true;
Cameras
Cameras define the viewing perspective of your 3D scene.
PerspectiveCamera
javascript
const camera = new [Link](
fov, // Field of view in degrees
aspect, // Aspect ratio (width/height)
near, // Near clipping plane
far // Far clipping plane
);
// Position the camera
[Link](x, y, z);
[Link](0, 0, 0); // Look at origin
OrthographicCamera
javascript
const camera = new [Link](
left, // Left boundary
right, // Right boundary
top, // Top boundary
bottom, // Bottom boundary
near, // Near clipping plane
far // Far clipping plane
);
Camera Controls
javascript
// Manual camera movement
[Link].x = 10;
[Link].y = 5;
[Link].z = 15;
// Look at a specific point
[Link](new THREE.Vector3(0, 0, 0));
// Update projection matrix after changes
[Link]();
Controls
Controls allow user interaction with the camera and scene.
OrbitControls (External Library)
javascript
// Include OrbitControls
// <script src="[Link]
const controls = new [Link](camera, [Link]);
[Link] = true; // Smooth camera movements
[Link] = 0.05;
[Link] = true;
[Link] = true;
[Link] = true;
// In animation loop
[Link]();
Manual Mouse Controls
javascript
let mouseX = 0, mouseY = 0;
[Link]('mousemove', (event) => {
mouseX = ([Link] / [Link]) * 2 - 1;
mouseY = -([Link] / [Link]) * 2 + 1;
});
// In animation loop
[Link].x = mouseX * 5;
[Link].y = mouseY * 5;
[Link]([Link]);
Textures
Textures add surface detail to materials.
Loading Textures
javascript
const textureLoader = new [Link]();
const texture = [Link]('path/to/[Link]');
// Apply to material
const material = new [Link]({
map: texture
});
Texture Properties
javascript
// Wrapping
[Link] = [Link];
[Link] = [Link];
[Link](2, 2);
// Filtering
[Link] = [Link];
[Link] = [Link];
// Offset and rotation
[Link](0.1, 0.1);
[Link] = [Link] / 4;
[Link](0.5, 0.5);
Texture Types
javascript
const material = new [Link]({
map: diffuseTexture, // Base color
normalMap: normalTexture, // Surface normals
roughnessMap: roughnessTexture, // Roughness variation
metalnessMap: metalnessTexture, // Metalness variation
emissiveMap: emissiveTexture, // Emissive areas
bumpMap: bumpTexture, // Height variation
displacementMap: dispTexture // Vertex displacement
});
Canvas Textures
javascript
const canvas = [Link]('canvas');
[Link] = 256;
[Link] = 256;
const context = [Link]('2d');
// Draw on canvas
[Link] = '#ff0000';
[Link](0, 0, 256, 256);
const texture = new [Link](canvas);
Animation
Animation brings life to 3D scenes.
Basic Animation Loop
javascript
function animate() {
requestAnimationFrame(animate);
// Update object properties
[Link].x += 0.01;
[Link].y += 0.01;
// Update controls if using
// [Link]();
[Link](scene, camera);
}
animate();
Clock for Time-based Animation
javascript
const clock = new [Link]();
function animate() {
requestAnimationFrame(animate);
const elapsedTime = [Link]();
// Smooth oscillation
[Link].y = [Link](elapsedTime) * 2;
[Link].z = elapsedTime * 0.5;
[Link](scene, camera);
}
[Link] Integration
javascript
// Include [Link]
// <script src="[Link]
// Create tween
const tween = new [Link]([Link])
.to({ x: 5, y: 5, z: 5 }, 2000)
.easing([Link])
.start();
// Update in animation loop
function animate() {
requestAnimationFrame(animate);
[Link]();
[Link](scene, camera);
}
Keyframe Animation
javascript
function createKeyframeAnimation(object, keyframes, duration) {
const startTime = [Link]();
function updateAnimation() {
const elapsed = ([Link]() - startTime) / duration;
const progress = [Link](elapsed, 1);
// Interpolate between keyframes
// Implementation depends on keyframe structure
if (progress < 1) {
requestAnimationFrame(updateAnimation);
}
}
updateAnimation();
}
Loading Models
[Link] supports various 3D model formats.
GLTFLoader (Recommended)
javascript
// Include GLTFLoader
// <script src="[Link]
const loader = new [Link]();
[Link]('models/[Link]', (gltf) => {
const model = [Link];
[Link](model);
// Access animations
if ([Link] > 0) {
const mixer = new [Link](model);
const action = [Link]([Link][0]);
[Link]();
}
});
OBJLoader
javascript
// Include OBJLoader
const loader = new [Link]();
[Link]('models/[Link]', (object) => {
[Link](object);
});
Loading with Progress
javascript
[Link](
'models/[Link]',
// onLoad
(gltf) => {
[Link]([Link]);
},
// onProgress
(progress) => {
[Link]('Loading progress:', [Link] / [Link]);
},
// onError
(error) => {
[Link]('Loading error:', error);
}
);
Helpers and Debug Tools
Debug tools help visualize and troubleshoot scenes.
Common Helpers
javascript
// Axis helper - shows X, Y, Z axes
const axesHelper = new [Link](5);
[Link](axesHelper);
// Grid helper - shows ground grid
const gridHelper = new [Link](10, 10);
[Link](gridHelper);
// Box helper - shows bounding box
const box = new THREE.Box3().setFromObject(mesh);
const boxHelper = new THREE.Box3Helper(box, 0xffff00);
[Link](boxHelper);
// Directional light helper
const dirLightHelper = new [Link](directionalLight, 5);
[Link](dirLightHelper);
// Camera helper
const cameraHelper = new [Link](camera);
[Link](cameraHelper);
[Link] for Performance
javascript
// Include [Link]
// <script src="[Link]
const stats = new Stats();
[Link]([Link]);
function animate() {
[Link]();
// Your animation code
[Link]();
requestAnimationFrame(animate);
}
[Link] for Controls
javascript
// Include [Link]
// <script src="[Link]
const gui = new [Link]();
const params = {
color: '#ff0000',
wireframe: false,
speed: 0.01
};
[Link](params, 'color').onChange((value) => {
[Link](value);
});
[Link](params, 'wireframe').onChange((value) => {
[Link] = value;
});
[Link](params, 'speed', 0, 0.1);
Performance Optimization
Geometry Optimization
javascript
// Merge geometries to reduce draw calls
const mergedGeometry = new [Link]();
[Link](geometry1);
[Link](geometry2);
// Use InstancedMesh for repeated objects
const instancedMesh = new [Link](geometry, material, count);
for (let i = 0; i < count; i++) {
const matrix = new THREE.Matrix4();
[Link](x, y, z);
[Link](i, matrix);
}
Rendering Optimization
javascript
// Set pixel ratio appropriately
[Link]([Link]([Link], 2));
// Use frustum culling
[Link]([Link], [Link]);
// Enable shadow map only when needed
[Link] = true;
[Link] = [Link]; // Faster than PCFSoftShadowMap
Level of Detail (LOD)
javascript
const lod = new [Link]();
[Link](highDetailMesh, 0); // Close distance
[Link](mediumDetailMesh, 50); // Medium distance
[Link](lowDetailMesh, 100); // Far distance
[Link](lod);
Object Pooling
javascript
class ObjectPool {
constructor(createFn, resetFn, initialSize = 10) {
[Link] = createFn;
[Link] = resetFn;
[Link] = [];
for (let i = 0; i < initialSize; i++) {
[Link]([Link]());
}
}
get() {
if ([Link] > 0) {
return [Link]();
}
return [Link]();
}
release(obj) {
[Link](obj);
[Link](obj);
}
}
Common Patterns
Raycasting for Mouse Interaction
javascript
const raycaster = new [Link]();
const mouse = new THREE.Vector2();
function onMouseClick(event) {
mouse.x = ([Link] / [Link]) * 2 - 1;
mouse.y = -([Link] / [Link]) * 2 + 1;
[Link](mouse, camera);
const intersects = [Link]([Link]);
if ([Link] > 0) {
const clickedObject = intersects[0].object;
// Handle click
}
}
[Link]('click', onMouseClick);
Scene Management
javascript
class SceneManager {
constructor() {
[Link] = new [Link]();
[Link] = new [Link]();
[Link] = new [Link]();
[Link] = new Map();
}
addObject(name, object) {
[Link](name, object);
[Link](object);
}
removeObject(name) {
const object = [Link](name);
if (object) {
[Link](object);
[Link](name);
}
}
render() {
[Link]([Link], [Link]);
}
}
Post-processing Effects
javascript
// Include EffectComposer and passes
// <script src="[Link]
// <script src="[Link]
const composer = new [Link](renderer);
[Link](new [Link](scene, camera));
// Add effects
const bloomPass = new [Link](
new THREE.Vector2([Link], [Link]),
1.5, 0.4, 0.85
);
[Link](bloomPass);
// Render with composer instead of renderer
[Link]();
Troubleshooting
Common Issues and Solutions
Nothing Appears on Screen
Check camera position and orientation
Ensure objects are within camera's view frustum
Verify renderer size matches container
Check if materials need lights (MeshBasicMaterial doesn't)
Performance Issues
Monitor draw calls (keep under 100 for mobile)
Use geometry merging or instancing
Optimize texture sizes
Enable frustum culling
Memory Leaks
javascript
// Dispose of geometries and materials
[Link]();
[Link]();
[Link]();
// Remove objects from scene
[Link](object);
// Clear renderer
[Link]();
Texture Loading Issues
javascript
// Handle texture load errors
[Link](
'[Link]',
(texture) => { /* Success */ },
undefined,
(error) => { [Link]('Texture failed to load:', error); }
);
// Check cross-origin issues
[Link] = 'anonymous';
Animation Stuttering
Use requestAnimationFrame properly
Check for blocking operations in animation loop
Monitor frame rate with [Link]
Consider using Web Workers for heavy computations
Debug Checklist
1. Console Errors: Check browser console for JavaScript errors
2. WebGL Support: Verify browser supports WebGL
3. Resource Loading: Confirm all assets load successfully
4. Scene Hierarchy: Use browser dev tools to inspect scene
5. Performance: Monitor FPS and memory usage
6. Mobile Testing: Test on mobile devices early
Useful Debug Code
javascript
// Log scene structure
function logScene(object, indent = '') {
[Link](indent + [Link], [Link] || 'unnamed');
[Link](child => logScene(child, indent + ' '));
}
logScene(scene);
// Check WebGL capabilities
[Link]('WebGL Max Texture Size:', [Link]);
[Link]('WebGL Extensions:', [Link]);
// Monitor memory usage
function logMemoryUsage() {
const info = [Link];
[Link]('Geometries:', [Link]);
[Link]('Textures:', [Link]);
[Link]('Render calls:', [Link]);
}
Conclusion
This documentation covers the fundamental concepts and common patterns in [Link] development.
The library's modular architecture and extensive ecosystem make it suitable for projects ranging from
simple visualizations to complex interactive experiences.
Key takeaways:
Start with basic scene setup and gradually add complexity
Performance optimization should be considered from the beginning
Use debug tools and helpers during development
The [Link] community and examples are excellent learning resources
For the latest features and updates, always refer to the official [Link] documentation at [Link].
This document serves as a comprehensive guide to [Link] development. For specific implementation details
and advanced topics, consult the official documentation and community resources.