JavaScript library for creating and displaying animated 3D computer graphics in web browsers
Core Idea: Three.js is a cross-browser JavaScript library that abstracts WebGL complexity, providing a high-level API for creating and rendering 3D graphics in web applications with minimal code.
Key Elements
Core Components
- Scene: Container that holds all objects, lights, and cameras
- Camera: Defines the viewpoint (perspective, orthographic, etc.)
- Renderer: Draws the scene from camera perspective (WebGL, CSS3D, SVG)
- Meshes: 3D objects composed of geometry and materials
- Materials: Define object appearance (color, texture, shininess)
- Geometries: Define object shape (vertices, faces, normals)
- Lights: Illuminate the scene with various light types
- Loaders: Import 3D models and textures from external files
Rendering Pipeline
- Scene Graph: Hierarchical organization of 3D objects
- Animation Loop: Continuous rendering for dynamic content
- Shaders: GLSL programs for advanced visual effects
- Post-processing: Effects applied after rendering (bloom, DOF)
- WebGL Integration: Low-level communication with graphics hardware
Development Workflow
- Setup: Creating renderer, scene, camera, and animation loop
- Scene Construction: Adding meshes, lights, and other objects
- Material Configuration: Applying colors, textures, and lighting properties
- Animation: Implementing motion and transformations
- Interaction: Adding user controls and event handling
- Optimization: Improving performance for complex scenes
Implementation Examples
Basic Scene Setup
// Create a scene
const scene = new THREE.Scene();
// Create a camera
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; // Position camera
// Create a renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Create a 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);
// Add lighting
const light = new THREE.AmbientLight(0x404040); // Soft white light
scene.add(light);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// Animation loop
function animate() {
requestAnimationFrame(animate);
// Rotate the cube
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
// Render the scene
renderer.render(scene, camera);
}
animate();
Advanced Material Usage
// Standard physically-based material
const standardMaterial = new THREE.MeshStandardMaterial({
color: 0x049ef4,
roughness: 0.5,
metalness: 0.7,
envMap: environmentTexture,
map: colorTexture,
normalMap: normalTexture,
aoMap: ambientOcclusionTexture,
displacementMap: heightTexture,
displacementScale: 0.2
});
// Creating a custom shader material
const customMaterial = new THREE.ShaderMaterial({
uniforms: {
time: { value: 1.0 },
resolution: { value: new THREE.Vector2() }
},
vertexShader: document.getElementById('vertexShader').textContent,
fragmentShader: document.getElementById('fragmentShader').textContent
});
Loading 3D Models
// GLTF loader example
const loader = new THREE.GLTFLoader();
loader.load(
'models/scene.gltf',
function(gltf) {
// Model loaded successfully
scene.add(gltf.scene);
// Access animations
const animations = gltf.animations;
const mixer = new THREE.AnimationMixer(gltf.scene);
const action = mixer.clipAction(animations[0]);
action.play();
},
function(xhr) {
// Loading progress
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
function(error) {
// Error occurred
console.error('An error happened', error);
}
);
Integration Approaches
Web Applications
- Single-page Applications: 3D visualization embedded in React, Vue, or Angular
- WebXR: Virtual and augmented reality experiences
- Data Visualization: 3D charts and interactive data exploration
- Product Configurators: Interactive 3D product customization
Mobile Integration
- React Native: Using Three.js via Expo GL or react-native-webgl
- Progressive Web Apps: Responsive 3D content for mobile browsers
- WebView Integration: Embedding Three.js content in native applications
- Performance Considerations: Optimization for mobile GPUs and battery life
Game Development
- Game Mechanics: Physics, collision detection, input handling
- Level Design: Procedural generation, terrain systems
- Entity Management: Game object hierarchies and interactions
- Multiplayer: Network synchronization of 3D scenes
- UI Integration: Combining 3D world with 2D interface elements
Optimization Techniques
-
Geometry Management:
- Use BufferGeometry for better performance
- Implement geometry instancing for repeated objects
- Apply level-of-detail (LOD) for distance-based simplification
-
Rendering Optimization:
- Frustum culling to skip rendering unseen objects
- Occlusion culling to avoid rendering hidden objects
- Object pooling to reduce garbage collection
-
Memory Management:
- Proper disposal of geometries and materials
- Texture compression and mipmapping
- Shared materials and geometries
-
Shader Optimization:
- Custom shader simplification for mobile
- Defer expensive calculations to vertex shader when possible
- Use shader chunks for code reusability
Ecosystem and Extensions
-
Official Extensions:
- Controls (OrbitControls, FlyControls, etc.)
- Effects (OutlineEffect, StereoEffect, etc.)
- Exporters and importers for various 3D formats
-
Community Addons:
- Physics engines (Ammo.js, Cannon.js, Oimo.js)
- Post-processing libraries
- Animation frameworks
- Particle systems
-
Development Tools:
- Three.js Editor for visual scene creation
- Three.js Inspector for debugging
- Performance analyzers (stats.js)
Connections
- Related Concepts: WebGL (underlying technology), 3D Graphics Fundamentals (theoretical basis), GLSL Shaders (extension point)
- Broader Context: Web Graphics Technologies (broader field), Browser-based Game Development (application area)
- Applications: Three.js in React Native (mobile implementation), Data Visualization (practical use)
- Components: Perlin Noise (used for procedural generation), 3D Asset Creation (content production)
References
- Three.js official documentation (https://threejs.org/docs/)
- "3D Graphics with Three.js" by various authors
- "WebGL Programming Guide" for underlying concepts
#three-js #webgl #3d-graphics #javascript #web-development
Connections:
Sources: