0
# Three.js
1
2
Three.js is a comprehensive JavaScript 3D library that creates an easy-to-use, lightweight, cross-browser, general-purpose 3D graphics solution for web applications. It provides WebGL and WebGPU renderers as core features, with additional SVG and CSS3D renderers available as addons. The library enables developers to create interactive 3D scenes, animations, and visualizations with support for virtual reality, augmented reality, WebXR, and various rendering techniques.
3
4
## Package Information
5
6
- **Package Name**: three
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install three`
10
11
## Core Imports
12
13
Main library import (includes core functionality and WebGL renderer):
14
15
```javascript
16
import * as THREE from 'three';
17
```
18
19
Selective imports:
20
21
```javascript
22
import {
23
Scene,
24
PerspectiveCamera,
25
WebGLRenderer,
26
BoxGeometry,
27
MeshBasicMaterial,
28
Mesh
29
} from 'three';
30
```
31
32
CommonJS:
33
34
```javascript
35
const THREE = require('three');
36
// or
37
const { Scene, PerspectiveCamera, WebGLRenderer } = require('three');
38
```
39
40
Specialized modules:
41
42
```javascript
43
// WebGPU renderer and nodes
44
import { WebGPURenderer } from 'three/webgpu';
45
46
// Three Shading Language (TSL)
47
import { color, vec3, uniform } from 'three/tsl';
48
49
// Addons/examples
50
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
51
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
52
```
53
54
## Basic Usage
55
56
```javascript
57
import * as THREE from 'three';
58
59
// Create scene
60
const scene = new THREE.Scene();
61
62
// Create camera
63
const camera = new THREE.PerspectiveCamera(
64
75, // field of view
65
window.innerWidth / window.innerHeight, // aspect ratio
66
0.1, // near clipping plane
67
1000 // far clipping plane
68
);
69
70
// Create renderer
71
const renderer = new THREE.WebGLRenderer();
72
renderer.setSize(window.innerWidth, window.innerHeight);
73
document.body.appendChild(renderer.domElement);
74
75
// Create geometry and material
76
const geometry = new THREE.BoxGeometry(1, 1, 1);
77
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
78
79
// Create mesh and add to scene
80
const cube = new THREE.Mesh(geometry, material);
81
scene.add(cube);
82
83
// Position camera
84
camera.position.z = 5;
85
86
// Render loop
87
function animate() {
88
requestAnimationFrame(animate);
89
90
// Rotate cube
91
cube.rotation.x += 0.01;
92
cube.rotation.y += 0.01;
93
94
// Render scene
95
renderer.render(scene, camera);
96
}
97
98
animate();
99
```
100
101
## Architecture
102
103
Three.js is built around several core architectural components:
104
105
- **Scene Graph**: Hierarchical organization of 3D objects using `Scene`, `Group`, and various `Object3D` derivatives
106
- **Renderers**: Multiple rendering backends (WebGL, WebGPU, SVG, CSS3D) that convert scene data into visual output
107
- **Math Library**: Comprehensive 3D mathematics including vectors, matrices, quaternions, and geometric operations
108
- **Material System**: Physically-based and non-physically-based materials with shader support
109
- **Geometry System**: Primitive and complex geometry types with efficient BufferGeometry implementation
110
- **Animation Framework**: Keyframe-based animation system with mixing, blending, and timeline control
111
- **Asset Loading**: Comprehensive loaders for 3D models, textures, audio, and other media formats
112
113
## Capabilities
114
115
### Core Scene Management
116
117
Essential components for creating and managing 3D scenes, including scene graphs, object hierarchies, and coordinate systems.
118
119
```javascript { .api }
120
class Scene extends Object3D {
121
constructor();
122
add(...objects: Object3D[]): this;
123
remove(...objects: Object3D[]): this;
124
getObjectByName(name: string): Object3D | undefined;
125
traverse(callback: (object: Object3D) => void): void;
126
}
127
128
class Object3D extends EventDispatcher {
129
position: Vector3;
130
rotation: Euler;
131
scale: Vector3;
132
matrix: Matrix4;
133
visible: boolean;
134
add(...objects: Object3D[]): this;
135
remove(...objects: Object3D[]): this;
136
clone(recursive?: boolean): this;
137
}
138
```
139
140
[Core Scene Management](./scene-management.md)
141
142
### Cameras
143
144
Camera systems for defining viewpoints and projections in 3D space, including perspective and orthographic cameras.
145
146
```javascript { .api }
147
class PerspectiveCamera extends Camera {
148
constructor(fov?: number, aspect?: number, near?: number, far?: number);
149
fov: number;
150
aspect: number;
151
near: number;
152
far: number;
153
updateProjectionMatrix(): void;
154
}
155
156
class OrthographicCamera extends Camera {
157
constructor(left?: number, right?: number, top?: number, bottom?: number, near?: number, far?: number);
158
left: number; right: number; top: number; bottom: number;
159
updateProjectionMatrix(): void;
160
}
161
```
162
163
[Cameras](./cameras.md)
164
165
### Renderers
166
167
Rendering engines that convert 3D scenes into 2D images, supporting multiple backends and rendering techniques.
168
169
```javascript { .api }
170
class WebGLRenderer extends EventDispatcher {
171
constructor(parameters?: WebGLRendererParameters);
172
domElement: HTMLCanvasElement;
173
render(scene: Object3D, camera: Camera): void;
174
setSize(width: number, height: number, updateStyle?: boolean): void;
175
setPixelRatio(value: number): void;
176
setClearColor(color: ColorRepresentation, alpha?: number): void;
177
}
178
179
interface WebGLRendererParameters {
180
canvas?: HTMLCanvasElement;
181
antialias?: boolean;
182
alpha?: boolean;
183
premultipliedAlpha?: boolean;
184
preserveDrawingBuffer?: boolean;
185
powerPreference?: string;
186
}
187
```
188
189
[Renderers](./renderers.md)
190
191
### Geometries
192
193
3D shape definitions including primitive shapes, complex geometries, and efficient buffer-based geometry system.
194
195
```javascript { .api }
196
class BufferGeometry extends EventDispatcher {
197
constructor();
198
attributes: { [name: string]: BufferAttribute };
199
index: BufferAttribute | null;
200
setAttribute(name: string, attribute: BufferAttribute): this;
201
computeBoundingBox(): void;
202
computeBoundingSphere(): void;
203
}
204
205
class BoxGeometry extends BufferGeometry {
206
constructor(width?: number, height?: number, depth?: number, widthSegments?: number, heightSegments?: number, depthSegments?: number);
207
}
208
```
209
210
[Geometries](./geometries.md)
211
212
### Materials
213
214
Surface appearance definitions including physically-based materials, shaders, and texture mapping systems.
215
216
```javascript { .api }
217
abstract class Material extends EventDispatcher {
218
transparent: boolean;
219
opacity: number;
220
side: Side;
221
visible: boolean;
222
clone(): this;
223
copy(source: Material): this;
224
}
225
226
class MeshStandardMaterial extends Material {
227
constructor(parameters?: MeshStandardMaterialParameters);
228
color: Color;
229
roughness: number;
230
metalness: number;
231
map: Texture | null;
232
normalMap: Texture | null;
233
}
234
```
235
236
[Materials](./materials.md)
237
238
### Lights
239
240
Illumination system supporting various light types, shadows, and lighting models for realistic scene rendering.
241
242
```javascript { .api }
243
abstract class Light extends Object3D {
244
color: Color;
245
intensity: number;
246
castShadow: boolean;
247
}
248
249
class DirectionalLight extends Light {
250
constructor(color?: ColorRepresentation, intensity?: number);
251
position: Vector3;
252
target: Object3D;
253
shadow: DirectionalLightShadow;
254
}
255
```
256
257
[Lights](./lights.md)
258
259
### Animation System
260
261
Keyframe-based animation framework with timeline control, blending, and complex animation sequencing.
262
263
```javascript { .api }
264
class AnimationMixer extends EventDispatcher {
265
constructor(root: Object3D);
266
clipAction(clip: AnimationClip, optionalRoot?: Object3D): AnimationAction;
267
update(deltaTimeInSeconds: number): AnimationMixer;
268
stopAllAction(): AnimationMixer;
269
}
270
271
class AnimationClip {
272
constructor(name?: string, duration?: number, tracks?: KeyframeTrack[]);
273
name: string;
274
duration: number;
275
tracks: KeyframeTrack[];
276
}
277
```
278
279
[Animation System](./animation.md)
280
281
### Math Utilities
282
283
Comprehensive 3D mathematics library including vectors, matrices, quaternions, and geometric calculations.
284
285
```javascript { .api }
286
class Vector3 {
287
constructor(x?: number, y?: number, z?: number);
288
x: number; y: number; z: number;
289
set(x: number, y: number, z: number): this;
290
add(v: Vector3): this;
291
multiply(v: Vector3): this;
292
length(): number;
293
normalize(): this;
294
}
295
296
class Matrix4 {
297
constructor();
298
elements: number[];
299
makeTranslation(x: number, y: number, z: number): this;
300
makeRotationFromEuler(euler: Euler): this;
301
multiply(m: Matrix4): this;
302
}
303
```
304
305
[Math Utilities](./math.md)
306
307
### Asset Loading
308
309
Comprehensive loading system for 3D models, textures, audio, and other assets with progress tracking and error handling.
310
311
```javascript { .api }
312
class TextureLoader extends Loader<Texture> {
313
constructor(manager?: LoadingManager);
314
load(url: string, onLoad?: (texture: Texture) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): Texture;
315
}
316
317
class LoadingManager {
318
constructor(onLoad?: () => void, onProgress?: (url: string, itemsLoaded: number, itemsTotal: number) => void, onError?: (url: string) => void);
319
onLoad: (() => void) | undefined;
320
onProgress: ((url: string, itemsLoaded: number, itemsTotal: number) => void) | undefined;
321
onError: ((url: string) => void) | undefined;
322
}
323
```
324
325
[Asset Loading](./loaders.md)
326
327
### WebGPU Rendering
328
329
Next-generation GPU rendering pipeline with compute shaders and advanced graphics capabilities.
330
331
```javascript { .api }
332
// Available via 'three/webgpu' import
333
class WebGPURenderer extends Renderer {
334
constructor(parameters?: WebGPURendererParameters);
335
compute(computeNodes: Node[]): Promise<void>;
336
computeAsync(computeNodes: Node[]): Promise<void>;
337
}
338
```
339
340
[WebGPU Rendering](./webgpu.md)
341
342
### Three Shading Language (TSL)
343
344
Node-based shading system for creating custom materials and effects with a JavaScript-friendly syntax.
345
346
```javascript { .api }
347
// Available via 'three/tsl' import
348
function color(value: ColorRepresentation): ColorNode;
349
function vec3(x?: NodeRepresentation, y?: NodeRepresentation, z?: NodeRepresentation): Vec3Node;
350
function uniform(value: any): UniformNode;
351
```
352
353
[Three Shading Language](./tsl.md)
354
355
## Types
356
357
```javascript { .api }
358
// Core type definitions used across the API
359
type ColorRepresentation = Color | string | number;
360
type Vector3Tuple = [number, number, number];
361
type EulerOrder = 'XYZ' | 'YZX' | 'ZXY' | 'XZY' | 'YXZ' | 'ZYX';
362
type Side = 0 | 1 | 2; // FrontSide | BackSide | DoubleSide
363
364
// Event system
365
interface Event {
366
type: string;
367
target?: any;
368
}
369
370
interface EventDispatcher {
371
addEventListener(type: string, listener: (event: Event) => void): void;
372
removeEventListener(type: string, listener: (event: Event) => void): void;
373
dispatchEvent(event: Event): void;
374
}
375
376
// Texture system
377
class Texture extends EventDispatcher {
378
constructor(image?: any, mapping?: number, wrapS?: number, wrapT?: number, magFilter?: number, minFilter?: number, format?: number, type?: number, anisotropy?: number, colorSpace?: string);
379
380
id: number;
381
uuid: string;
382
name: string;
383
image: any;
384
mapping: number;
385
wrapS: number;
386
wrapT: number;
387
magFilter: number;
388
minFilter: number;
389
format: number;
390
type: number;
391
anisotropy: number;
392
colorSpace: string;
393
394
offset: Vector2;
395
repeat: Vector2;
396
center: Vector2;
397
rotation: number;
398
399
generateMipmaps: boolean;
400
premultiplyAlpha: boolean;
401
flipY: boolean;
402
unpackAlignment: number;
403
404
needsUpdate: boolean;
405
onUpdate: () => void;
406
407
clone(): this;
408
copy(source: Texture): this;
409
dispose(): void;
410
}
411
412
// Time utilities
413
class Clock {
414
constructor(autoStart?: boolean);
415
416
autoStart: boolean;
417
startTime: number;
418
oldTime: number;
419
elapsedTime: number;
420
running: boolean;
421
422
start(): void;
423
stop(): void;
424
getElapsedTime(): number;
425
getDelta(): number;
426
}
427
428
class Timer {
429
constructor();
430
431
update(): this;
432
reset(): this;
433
connect(document: Document): this;
434
disconnect(): this;
435
dispose(): this;
436
437
getDelta(): number;
438
getElapsed(): number;
439
getTimescale(): number;
440
setTimescale(scale: number): this;
441
}
442
```