
Threejs
- 1 installs
- 2 repo stars
- Updated August 3, 2026
- fandhe-ai/agent-reference-skills
Reference the Three.js API for 3D web graphics including animation (AnimationAction, AnimationMixer, clips), scenes, and rendering primitives.
About
A structured reference for Three.js covering the 3D graphics API including the animation system (AnimationAction, AnimationMixer, clips) and related primitives. A developer loads it when building WebGL 3D scenes and animations.
- AnimationAction scheduling via AnimationMixer.clipAction
- Signature and constructor documentation per class
Threejs by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,366 of 1,879 Documentation skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/fandhe-ai/agent-reference-skills --skill threejsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 3, 2026 |
| Repository | fandhe-ai/agent-reference-skills ↗ |
What it does
Reference the Three.js API for 3D web graphics including animation (AnimationAction, AnimationMixer, clips), scenes, and rendering primitives.
Files
AnimationAction
Schedules the playback of an AnimationClip on an AnimationMixer. Controls when the clip plays, how it loops, fade behavior, time scaling, and crossfading with other actions.
Signature / Usage
// Do not instantiate directly — use AnimationMixer.clipAction()
const mixer = new THREE.AnimationMixer(mesh);
const action = mixer.clipAction(clip);
action.play();Constructor
new AnimationAction(mixer, clip, localRoot, blendMode)| Parameter | Type | Description |
|---|---|---|
| mixer | AnimationMixer | The mixer that controls this action |
| clip | AnimationClip | The animation clip holding keyframes |
| localRoot | Object3D | Root object for the action (default: null) |
| blendMode | NormalAnimationBlendMode \ | AdditiveAnimationBlendMode |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| blendMode | number | NormalAnimationBlendMode | Blending mode when multiple animations play simultaneously |
| clampWhenFinished | boolean | false | If true, pauses on last frame when finished; if false, disables the action |
| enabled | boolean | true | If false, the action has no effect |
| loop | LoopRepeat \ | LoopOnce \ | LoopPingPong |
| paused | boolean | false | Whether playback is paused |
| repetitions | number | Infinity | Number of clip repetitions (ignored when loop is LoopOnce) |
| time | number | 0 | Local time in seconds, clamped/wrapped to [0, clip.duration] |
| timeScale | number | 1 | Scaling factor for time; 0 pauses, negative plays backwards |
| weight | number | 1 | Influence weight in range [0, 1] for blending |
| zeroSlopeAtEnd | boolean | true | Enables smooth interpolation at clip end |
| zeroSlopeAtStart | boolean | true | Enables smooth interpolation at clip start |
Methods
Playback control:
| Method | Returns | Description |
|---|---|---|
| play() | AnimationAction | Starts/resumes playback |
| stop() | AnimationAction | Stops playback and resets |
| reset() | AnimationAction | Resets time, paused, enabled, weight, timeScale |
| halt(duration) | AnimationAction | Decelerates speed to 0 over given duration |
Fading and transitions:
| Method | Returns | Description |
|---|---|---|
| fadeIn(duration) | AnimationAction | Fades weight from 0 to 1 over duration |
| fadeOut(duration) | AnimationAction | Fades weight from 1 to 0 over duration |
| crossFadeFrom(fadeOutAction, duration, warp) | AnimationAction | This action fades in while another fades out |
| crossFadeTo(fadeInAction, duration, warp) | AnimationAction | This action fades out while another fades in |
| stopFading() | AnimationAction | Stops any active fade |
| warp(startTimeScale, endTimeScale, duration) | AnimationAction | Gradually changes playback speed |
| stopWarping() | AnimationAction | Stops scheduled warping |
Configuration:
| Method | Returns | Description |
|---|---|---|
| setLoop(mode, repetitions) | AnimationAction | Sets loop mode and repetition count |
| setDuration(duration) | AnimationAction | Sets the duration of a single loop |
| setEffectiveTimeScale(timeScale) | AnimationAction | Sets effective time scale |
| setEffectiveWeight(weight) | AnimationAction | Sets effective weight |
| startAt(time) | AnimationAction | Schedules when the action should start (global mixer time) |
| syncWith(action) | AnimationAction | Synchronizes time and timeScale with another action |
State queries:
| Method | Returns | Description |
|---|---|---|
| isRunning() | boolean | True if currently playing |
| isScheduled() | boolean | True if play() has been called |
| getClip() | AnimationClip | Returns the associated clip |
| getMixer() | AnimationMixer | Returns the controlling mixer |
| getRoot() | Object3D | Returns the root object |
| getEffectiveTimeScale() | number | Returns effective time scale |
| getEffectiveWeight() | number | Returns effective weight |
Notes
- Do not use the constructor directly; always obtain actions via
AnimationMixer.clipAction(). clampWhenFinishedonly takes effect ifloopis set toLoopOnce.- Methods returning
AnimationActionsupport method chaining.
Related
- AnimationMixer
- AnimationClip
AnimationClip
A reusable set of KeyframeTrack instances representing a single animation (e.g., a walk cycle or a jump). Clips are typically created automatically by loaders such as GLTFLoader.
Signature / Usage
// Usually obtained from a loaded model
const { animations } = await loader.loadAsync('model.glb');
const walkClip = THREE.AnimationClip.findByName(animations, 'walk');
const action = mixer.clipAction(walkClip);
action.play();Constructor
new AnimationClip(name, duration, tracks, blendMode)| Parameter | Type | Default | Description |
|---|---|---|---|
| name | string | '' | Clip name |
| duration | number | -1 | Duration in seconds; if negative, calculated from tracks |
| tracks | Array\<KeyframeTrack\> | — | Array of keyframe tracks |
| blendMode | NormalAnimationBlendMode \ | AdditiveAnimationBlendMode | NormalAnimationBlendMode |
Properties
| Name | Type | Description |
|---|---|---|
| blendMode | number | Blending behavior when multiple animations run simultaneously |
| duration | number | Duration in seconds |
| name | string | Clip name |
| tracks | Array\<KeyframeTrack\> | Keyframe tracks composing this clip |
| userData | Object | Custom data (avoid storing function references) |
| uuid | string | Read-only unique identifier |
Methods
| Method | Returns | Description |
|---|---|---|
| clone() | AnimationClip | Returns a copy |
| optimize() | AnimationClip | Removes redundant sequential keys from tracks |
| resetDuration() | AnimationClip | Sets duration to the longest track's duration |
| toJSON() | Object | Serializes to JSON |
| trim() | AnimationClip | Trims all tracks to the clip's duration |
| validate() | boolean | Validates all tracks; returns true if valid |
Static Methods
| Method | Returns | Description |
|---|---|---|
| AnimationClip.findByName(objectOrClipArray, name) | AnimationClip | Finds a clip by name |
| AnimationClip.parse(json) | AnimationClip | Creates a clip from a JSON object |
| AnimationClip.toJSON(clip) | Object | Serializes a clip to JSON |
| AnimationClip.CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) | AnimationClip | Creates a clip from a morph target sequence |
| AnimationClip.CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) | Array\<AnimationClip\> | Creates multiple clips from morph target sequences |
Notes
parseAnimation(parsesanimation.hierarchyformat) is deprecated since r175.- When loading from GLTF/FBX, prefer
AnimationClip.findByName()over array indexing to select clips by name.
Related
- AnimationMixer
- AnimationAction
- KeyframeTrack
AnimationMixer
A player for animations on a particular scene object. For multiple independently animated objects, create one mixer per object. Must be updated each frame via mixer.update(delta).
Signature / Usage
const mixer = new THREE.AnimationMixer(mesh);
const action = mixer.clipAction(clip);
action.play();
// In render loop:
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
mixer.update(clock.getDelta());
renderer.render(scene, camera);
}
animate();Constructor
new AnimationMixer(root: Object3D)| Parameter | Type | Description |
|---|---|---|
| root | Object3D | The object whose animations this mixer plays |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| time | number | 0 | Global mixer time in seconds |
| timeScale | number | 1 | Scaling factor for global time; set to 0 to pause all actions, back to 1 to resume |
Methods
| Method | Returns | Description |
|---|---|---|
| clipAction(clip, optionalRoot?, blendMode?) | AnimationAction | Returns (or creates) an action for the given clip. Always returns the same instance for the same parameters. |
| existingAction(clip, optionalRoot?) | AnimationAction \ | null |
| getRoot() | Object3D | Returns the mixer's root object |
| setTime(time) | AnimationMixer | Jumps to a specific time (scaled by timeScale) |
| stopAllAction() | AnimationMixer | Deactivates all scheduled actions |
| update(deltaTime) | AnimationMixer | Advances mixer time and updates animations; call once per frame |
| uncacheAction(clip, optionalRoot?) | void | Frees memory for an action; call action.stop() first |
| uncacheClip(clip) | void | Frees memory for a clip; stop all related actions first |
| uncacheRoot(root) | void | Frees memory for a root object; stop all related actions first |
Notes
clipAction()is the primary way to obtain anAnimationAction; it caches internally so repeated calls with the same arguments return the same object.- Always call
stop()on related actions before using anyuncache*method to avoid memory leaks. - Use
timeScale = 0to pause all animations without losing their state.
Related
- AnimationAction
- AnimationClip
- AnimationObjectGroup
AnimationObjectGroup
A group of objects that share a single animation state. Pass an AnimationObjectGroup as the root to AnimationMixer or clipAction() to animate multiple objects together.
Signature / Usage
const group = new THREE.AnimationObjectGroup(meshA, meshB);
const mixer = new THREE.AnimationMixer(group);
const action = mixer.clipAction(clip);
action.play();
// Add/remove objects dynamically
group.add(meshC);
group.remove(meshA);Constructor
new AnimationObjectGroup(...objects: Object3D)| Parameter | Type | Description |
|---|---|---|
| ...objects | Object3D | Initial objects to include in the group |
Properties
| Name | Type | Description |
|---|---|---|
| isAnimationObjectGroup | boolean | Read-only type flag; always true |
| uuid | string | Read-only unique identifier |
Methods
| Method | Description |
|---|---|
| add(...objects: Object3D) | Adds objects to the group |
| remove(...objects: Object3D) | Removes objects from the group |
| uncache(...objects: Object3D) | Frees memory resources for the given objects |
Notes
- All objects in the group must have compatible animated properties (same property names and value sizes).
- A property can be controlled either through a group or directly on an object — not both at the same time.
- Cache management must be done at the group level; individual object uncaching is done via
uncache().
Related
- AnimationMixer
- AnimationAction
AnimationUtils
A utility class providing static helper methods for animation operations, including keyframe manipulation, clip conversion, and typed array processing. All methods are static.
Signature / Usage
// Create a sub-segment of an animation clip
const runClip = THREE.AnimationUtils.subclip(sourceClip, 'run', 10, 30, 30);
// Convert a clip to additive blending format
const additiveClip = THREE.AnimationUtils.makeClipAdditive(clip);Static Methods
| Method | Returns | Description |
|---|---|---|
| convertArray(array, type) | TypedArray | Converts an array to the specified typed array type |
| flattenJSON(jsonKeys, times, values, valuePropertyName) | void | Parses AOS keyframe format; populates times and values arrays |
| getKeyframeOrder(times) | Array\<number\> | Returns sort-order indices for the given times array |
| isTypedArray(object) | boolean | Returns true if the object is a typed array |
| makeClipAdditive(targetClip, referenceFrame?, referenceClip?, fps?) | AnimationClip | Converts clip keyframes to additive format |
| sortedArray(values, stride, order) | Array\<number\> | Sorts values using a pre-computed order from getKeyframeOrder() |
| subclip(sourceClip, name, startFrame, endFrame, fps?) | AnimationClip | Creates a new clip containing only the specified frame range |
subclip Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| sourceClip | AnimationClip | — | Source clip to extract from |
| name | string | — | Name for the new clip |
| startFrame | number | — | Starting frame number |
| endFrame | number | — | Ending frame number |
| fps | number | 30 | Frames per second used for frame-to-time conversion |
makeClipAdditive Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| targetClip | AnimationClip | — | Clip to convert to additive format |
| referenceFrame | number | 0 | Reference frame for the base pose |
| referenceClip | AnimationClip | targetClip | Clip providing the reference pose |
| fps | number | 30 | Frames per second |
Notes
subclipis useful for splitting a single long animation clip exported from a DCC tool into multiple named actions.makeClipAdditiveis required when usingAdditiveAnimationBlendModeon anAnimationAction.
Related
- AnimationClip
- AnimationAction
KeyframeTrack
A timed sequence of keyframes that animates a specific property of an object. Stores parallel arrays of times and values. This is the base class for all concrete track types.
Signature / Usage
// Animate position.x from 0 to 10 over 2 seconds
const track = new THREE.VectorKeyframeTrack(
'mesh.position',
[0, 1, 2],
[0, 0, 0, 5, 0, 0, 10, 0, 0]
);
const clip = new THREE.AnimationClip('move', 2, [track]);Constructor
new KeyframeTrack(name, times, values, interpolation)| Parameter | Type | Description |
|---|---|---|
| name | string | Track name; references a property path (e.g., '.position', 'boneName.quaternion') |
| times | Array\<number\> | Keyframe times in seconds |
| values | Array | Keyframe values (number, string, or boolean depending on subclass) |
| interpolation | InterpolateLinear \ | InterpolateDiscrete \ |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| DefaultInterpolation | number | InterpolateLinear | Default interpolation type for this track class |
| TimeBufferType | constructor | Float32Array | Buffer type for time values |
| ValueBufferType | constructor | Float32Array | Buffer type for property values |
| ValueTypeName | string | '' | String identifier for value type (overridden by subclasses) |
| name | string | — | Property path this track targets |
| times | Float32Array | — | Keyframe times |
| values | Float32Array | — | Keyframe values |
Methods
| Method | Returns | Description |
|---|---|---|
| clone() | KeyframeTrack | Returns a copy |
| getInterpolation() | number | Returns the current interpolation type constant |
| getValueSize() | number | Returns the number of values per keyframe |
| optimize() | KeyframeTrack | Removes redundant sequential keys |
| scale(timeScale) | KeyframeTrack | Multiplies all keyframe times by timeScale |
| setInterpolation(interpolation) | KeyframeTrack | Changes the interpolation method |
| shift(timeOffset) | KeyframeTrack | Shifts all keyframe times by timeOffset seconds |
| trim(startTime, endTime) | KeyframeTrack | Removes keyframes outside the specified time range |
| validate() | boolean | Returns true if track data is valid |
| InterpolantFactoryMethodLinear(result) | LinearInterpolant | Creates a linear interpolant |
| InterpolantFactoryMethodDiscrete(result) | DiscreteInterpolant | Creates a discrete interpolant |
| InterpolantFactoryMethodSmooth(result) | CubicInterpolant | Creates a smooth (cubic) interpolant |
| InterpolantFactoryMethodBezier(result) | BezierInterpolant | Creates a Bezier interpolant (requires settings.inTangents/outTangents) |
Static Methods
| Method | Returns | Description |
|---|---|---|
| KeyframeTrack.toJSON(track) | Object | Serializes a track to JSON |
Notes
trim()does not shift remaining keys to time 0; this would alter interpolated values.- For Bezier interpolation, set
settings.inTangentsandsettings.outTangentson the track before creating the interpolant. - Use concrete subclasses (
VectorKeyframeTrack,QuaternionKeyframeTrack, etc.) rather than this base class directly.
Related
- AnimationClip
- tracks/VectorKeyframeTrack
- tracks/QuaternionKeyframeTrack
- tracks/NumberKeyframeTrack
- tracks/ColorKeyframeTrack
- tracks/BooleanKeyframeTrack
- tracks/StringKeyframeTrack
PropertyBinding
Holds a reference to an animated property in the scene graph and provides getter/setter pairs for reading and writing it. Used internally by the animation system; rarely instantiated directly.
Constructor
new PropertyBinding(rootNode, path, parsedPath)| Parameter | Type | Description |
|---|---|---|
| rootNode | Object3D \ | Skeleton |
| path | string | Dot-separated path to the animated property |
| parsedPath | Object | Pre-parsed path object (optional) |
Properties
| Name | Type | Description |
|---|---|---|
| node | Object | The object owning the animated property |
| parsedPath | Object | Parsed representation of the property path |
| path | string | Raw path string to the animated property |
| rootNode | Object3D \ | Skeleton |
Methods
| Method | Description |
|---|---|
| bind() | Creates getter/setter pair for the target property |
| unbind() | Releases the getter/setter pair |
Static Methods
| Method | Returns | Description |
|---|---|---|
| PropertyBinding.create(root, path, parsedPath?) | PropertyBinding \ | Composite |
| PropertyBinding.findNode(root, nodeName) | Object \ | null |
| PropertyBinding.parseTrackName(trackName) | Object | Parses a track name string into path components |
| PropertyBinding.sanitizeNodeName(name) | string | Replaces spaces with underscores and removes unsupported characters |
Notes
- Track name formats supported by
parseTrackName: nodeName.propertynodeName.property[index]nodeName.subObject.property[index]uuid.property[index]parentName/nodeName.property.bone[Armature.DEF_cog].position
Related
- PropertyMixer
- KeyframeTrack
PropertyMixer
A buffered scene-graph property manager that supports weighted accumulation of values from multiple animation sources. Used internally by the animation system for blending; rarely instantiated directly.
Constructor
new PropertyMixer(binding, typeName, valueSize)| Parameter | Type | Description |
|---|---|---|
| binding | PropertyBinding | The property binding to manage |
| typeName | string | The keyframe track type name (e.g., 'vector', 'quaternion') |
| valueSize | number | Number of values per keyframe sample |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| binding | PropertyBinding | — | The underlying property binding |
| cumulativeWeight | number | 0 | Total accumulated weight (normal blending) |
| cumulativeWeightAdditive | number | 0 | Total accumulated additive weight |
| referenceCount | number | 0 | Number of keyframe tracks referencing this binding |
| useCount | number | 0 | Number of active keyframe tracks currently using this binding |
| valueSize | number | — | Number of values per keyframe sample |
Methods
| Method | Description |
|---|---|
| accumulate(accuIndex, weight) | Accumulates the incoming region's data into accumulation buffer accuIndex |
| accumulateAdditive(weight) | Accumulates incoming data into the additive buffer |
| apply(accuIndex) | Applies accumulation buffer accuIndex to the binding when it differs from current state |
| saveOriginalState() | Saves the current bound property value to both accumulation buffers |
| restoreOriginalState() | Applies the saved original state back to the binding |
Notes
- This class is part of the internal animation blending pipeline and is managed automatically by
AnimationMixer. referenceCountanduseCountare used to determine when aPropertyMixercan be safely removed from the cache.
Related
- PropertyBinding
- AnimationMixer
Animation
Three.js animation system classes for playing, blending, and managing keyframe animations.
| Name | Description | Path |
|---|---|---|
| AnimationAction | Controls playback of an AnimationClip on a mixer (play, stop, fade, crossfade) | AnimationAction.md |
| AnimationClip | Reusable set of KeyframeTracks representing a single animation | AnimationClip.md |
| AnimationMixer | Player for animations on a scene object; must be updated each frame | AnimationMixer.md |
| AnimationObjectGroup | Group of objects sharing a single animation state | AnimationObjectGroup.md |
| AnimationUtils | Static utilities for subclipping, additive conversion, and array manipulation | AnimationUtils.md |
| KeyframeTrack | Base class for timed keyframe sequences targeting a scene property | KeyframeTrack.md |
| PropertyBinding | Internal binding between a track name and a real scene graph property | PropertyBinding.md |
| PropertyMixer | Internal buffered property manager for weighted animation blending | PropertyMixer.md |
| tracks/ | Concrete KeyframeTrack subclasses (Boolean, Color, Number, Quaternion, String, Vector) | tracks/README.md |
BooleanKeyframeTrack
A KeyframeTrack for boolean values. Uses discrete interpolation only; no interpolation parameter is accepted.
Constructor
new BooleanKeyframeTrack(name, times, values)| Parameter | Type | Description |
|---|---|---|
| name | string | Track name / property path |
| times | Array\<number\> | Keyframe times in seconds |
| values | Array\<boolean\> | Keyframe boolean values |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| DefaultInterpolation | number | InterpolateDiscrete | Overrides KeyframeTrack#DefaultInterpolation |
| ValueBufferType | constructor | Array | Overrides KeyframeTrack#ValueBufferType |
| ValueTypeName | string | 'bool' | Overrides KeyframeTrack#ValueTypeName |
Notes
- Does not accept an interpolation parameter — boolean values are always discrete.
- Inherits all methods from
KeyframeTrack.
Related
- KeyframeTrack
ColorKeyframeTrack
A KeyframeTrack for RGB color values. Values are stored as flat arrays of R, G, B components (each in range [0, 1]) interleaved per keyframe.
Signature / Usage
const track = new THREE.ColorKeyframeTrack(
'material.color',
[0, 1, 2], // times
[1, 0, 0, 0, 1, 0, 0, 0, 1], // red → green → blue
THREE.InterpolateLinear
);Constructor
new ColorKeyframeTrack(name, times, values, interpolation)| Parameter | Type | Description |
|---|---|---|
| name | string | Track name / property path |
| times | Array\<number\> | Keyframe times in seconds |
| values | Array\<number\> | Keyframe RGB values (3 numbers per keyframe) |
| interpolation | InterpolateLinear \ | InterpolateDiscrete \ |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| ValueTypeName | string | 'color' | Overrides KeyframeTrack#ValueTypeName |
Notes
- Values array has 3 elements per keyframe (R, G, B).
- Inherits all methods from
KeyframeTrack.
Related
- KeyframeTrack
NumberKeyframeTrack
A KeyframeTrack for scalar numeric values. Suitable for animating opacity, morph target influences, or any single-number property.
Signature / Usage
const track = new THREE.NumberKeyframeTrack(
'mesh.material.opacity',
[0, 1], // times
[1, 0], // values: fade from opaque to transparent
THREE.InterpolateLinear
);Constructor
new NumberKeyframeTrack(name, times, values, interpolation)| Parameter | Type | Description |
|---|---|---|
| name | string | Track name / property path |
| times | Array\<number\> | Keyframe times in seconds |
| values | Array\<number\> | Keyframe numeric values (1 number per keyframe) |
| interpolation | InterpolateLinear \ | InterpolateDiscrete \ |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| ValueTypeName | string | 'number' | Overrides KeyframeTrack#ValueTypeName |
Notes
- Values array has 1 element per keyframe.
- Inherits all methods from
KeyframeTrack.
Related
- KeyframeTrack
QuaternionKeyframeTrack
A KeyframeTrack for quaternion rotation values. Values are stored as flat arrays of X, Y, Z, W components per keyframe. Uses QuaternionLinearInterpolant (SLERP) for linear interpolation to ensure correct spherical rotation blending.
Signature / Usage
const track = new THREE.QuaternionKeyframeTrack(
'bone.quaternion',
[0, 1],
[0, 0, 0, 1, 0, 0.707, 0, 0.707] // identity → 90° rotation around Y
);Constructor
new QuaternionKeyframeTrack(name, times, values, interpolation)| Parameter | Type | Description |
|---|---|---|
| name | string | Track name / property path |
| times | Array\<number\> | Keyframe times in seconds |
| values | Array\<number\> | Quaternion components (4 numbers per keyframe: X, Y, Z, W) |
| interpolation | InterpolateLinear \ | InterpolateDiscrete \ |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| ValueTypeName | string | 'quaternion' | Overrides KeyframeTrack#ValueTypeName |
Methods
| Method | Returns | Description |
|---|---|---|
| InterpolantFactoryMethodLinear(result) | QuaternionLinearInterpolant | Creates a SLERP-based interpolant; overrides the parent linear factory |
Notes
- Values array has 4 elements per keyframe (X, Y, Z, W).
- Linear interpolation uses SLERP (
QuaternionLinearInterpolant) rather than standard linear interpolation to avoid gimbal lock. - Inherits all other methods from
KeyframeTrack.
Related
- KeyframeTrack
KeyframeTracks
Concrete KeyframeTrack subclasses for each value type used in Three.js animations.
| Name | Description | Path |
|---|---|---|
| BooleanKeyframeTrack | Discrete boolean keyframes (no interpolation) | BooleanKeyframeTrack.md |
| ColorKeyframeTrack | RGB color keyframes (3 values per keyframe) | ColorKeyframeTrack.md |
| NumberKeyframeTrack | Scalar numeric keyframes (1 value per keyframe) | NumberKeyframeTrack.md |
| QuaternionKeyframeTrack | Quaternion rotation keyframes using SLERP (4 values per keyframe) | QuaternionKeyframeTrack.md |
| StringKeyframeTrack | Discrete string keyframes (no interpolation) | StringKeyframeTrack.md |
| VectorKeyframeTrack | Vector (position/scale) keyframes (N values per keyframe) | VectorKeyframeTrack.md |
StringKeyframeTrack
A KeyframeTrack for string values. Uses discrete interpolation only; no interpolation parameter is accepted.
Constructor
new StringKeyframeTrack(name, times, values)| Parameter | Type | Description |
|---|---|---|
| name | string | Track name / property path |
| times | Array\<number\> | Keyframe times in seconds |
| values | Array\<string\> | Keyframe string values |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| DefaultInterpolation | number | InterpolateDiscrete | Overrides KeyframeTrack#DefaultInterpolation |
| ValueBufferType | constructor | Array | Overrides KeyframeTrack#ValueBufferType |
| ValueTypeName | string | 'string' | Overrides KeyframeTrack#ValueTypeName |
Notes
- Does not accept an interpolation parameter — string values are always discrete.
- Inherits all methods from
KeyframeTrack.
Related
- KeyframeTrack
VectorKeyframeTrack
A KeyframeTrack for vector values (e.g., Vector2, Vector3). Values are stored as flat arrays of components interleaved per keyframe.
Signature / Usage
// Animate position along a path (Vector3: 3 values per keyframe)
const track = new THREE.VectorKeyframeTrack(
'mesh.position',
[0, 1, 2],
[0, 0, 0, 10, 0, 0, 10, 10, 0]
);Constructor
new VectorKeyframeTrack(name, times, values, interpolation)| Parameter | Type | Description |
|---|---|---|
| name | string | Track name / property path |
| times | Array\<number\> | Keyframe times in seconds |
| values | Array\<number\> | Vector component values (N numbers per keyframe, where N is the vector size) |
| interpolation | InterpolateLinear \ | InterpolateDiscrete \ |
Properties
| Name | Type | Default | Description |
|---|---|---|---|
| ValueTypeName | string | 'vector' | Overrides KeyframeTrack#ValueTypeName |
Notes
- The number of values per keyframe matches the vector dimension (2 for Vector2, 3 for Vector3).
- Inherits all methods from
KeyframeTrack.
Related
- KeyframeTrack
ArrayCamera
A camera that contains an array of sub-cameras (PerspectiveCamera) for efficiently rendering a scene multiple times per frame. Primarily used for VR rendering.
Signature / Usage
const cameras = [
new THREE.PerspectiveCamera(75, window.innerWidth / 2 / window.innerHeight, 0.1, 1000),
new THREE.PerspectiveCamera(75, window.innerWidth / 2 / window.innerHeight, 0.1, 1000),
];
cameras[0].viewport = new THREE.Vector4(0, 0, window.innerWidth / 2, window.innerHeight);
cameras[1].viewport = new THREE.Vector4(window.innerWidth / 2, 0, window.innerWidth / 2, window.innerHeight);
const arrayCamera = new THREE.ArrayCamera(cameras);Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
cameras | Array<PerspectiveCamera> | [] | Array of perspective sub-cameras; each must have a viewport property |
isArrayCamera | boolean (readonly) | true | Type-testing flag |
isMultiViewCamera | boolean (readonly) | false | Whether the camera uses multiview rendering |
Notes
- Each sub-camera must have a
viewport(Vector4) set to define which portion of the output it renders to. - Inherits from
PerspectiveCamera, which inherits fromCamera.
Related
- Camera
- PerspectiveCamera
Camera
Abstract base class for all Three.js cameras. Not instantiated directly — extend it when building a custom camera type.
Inheritance
EventDispatcher → Object3D → Camera
Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
coordinateSystem | `WebGLCoordinateSystem \ | WebGPUCoordinateSystem` | — |
isCamera | boolean (readonly) | true | Type-testing flag |
matrixWorldInverse | Matrix4 | — | Inverse of the camera's world matrix |
projectionMatrix | Matrix4 | — | The camera's projection matrix |
projectionMatrixInverse | Matrix4 | — | Inverse of the projection matrix |
reversedDepth | boolean | false | Whether the camera uses a reversed depth buffer |
Methods
getWorldDirection(target: Vector3): Vector3
Returns a Vector3 representing the camera's look direction in world space. Cameras look down their local negative z-axis by default.
Notes
- This class overrides
Object3D.getWorldDirection()because cameras face the negative z-axis rather than positive z. - All concrete camera classes (
PerspectiveCamera,OrthographicCamera, etc.) inherit from this class.
Related
- PerspectiveCamera
- OrthographicCamera
- ArrayCamera
- CubeCamera
- StereoCamera
CubeCamera
Renders the scene from a single point into a WebGLCubeRenderTarget, producing a cube map that can be used as a real-time reflection or environment map.
Signature / Usage
const cubeRenderTarget = new THREE.WebGLCubeRenderTarget(256, {
generateMipmaps: true,
minFilter: THREE.LinearMipmapLinearFilter,
});
const cubeCamera = new THREE.CubeCamera(1, 100000, cubeRenderTarget);
scene.add(cubeCamera);
// Use the cube map as an environment/reflection map
const material = new THREE.MeshLambertMaterial({
envMap: cubeRenderTarget.texture,
});
// Each frame: hide the reflective object, update, then show again
object.visible = false;
cubeCamera.position.copy(object.position);
cubeCamera.update(renderer, scene);
object.visible = true;Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
near | number | — | Near clipping plane (constructor parameter) |
far | number | — | Far clipping plane (constructor parameter) |
renderTarget | WebGLCubeRenderTarget | — | The cube render target to render into |
activeMipmapLevel | number | 0 | Active mipmap level to render to |
coordinateSystem | `WebGLCoordinateSystem \ | WebGPUCoordinateSystem \ | null` |
Methods
| Method | Returns | Description |
|---|---|---|
update(renderer, scene) | void | Renders the scene into the cube render target from this camera's position |
updateCoordinateSystem() | void | Must be called when the camera's coordinate system changes |
Notes
- Inherits from
Object3D, not from theCamerabase class. - Typically the reflective object should be hidden before calling
update()to avoid self-reflection artifacts.
Related
- Camera
- PerspectiveCamera
OrthographicCamera
A camera using orthographic projection. Objects appear the same size regardless of distance from the camera. Useful for 2D scenes and UI elements.
Signature / Usage
const camera = new THREE.OrthographicCamera(
width / -2, width / 2,
height / 2, height / -2,
1, 1000
);
scene.add(camera);Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
left | number | -1 | Left plane of the frustum |
right | number | 1 | Right plane of the frustum |
top | number | 1 | Top plane of the frustum |
bottom | number | -1 | Bottom plane of the frustum |
near | number | 0.1 | Near clipping plane (can be 0) |
far | number | 2000 | Far clipping plane (must be > near) |
zoom | number | 1 | Zoom factor |
view | `Object \ | null` | null |
isOrthographicCamera | boolean (readonly) | true | Type-testing flag |
Methods
| Method | Returns | Description |
|---|---|---|
updateProjectionMatrix() | void | Must be called after any property change |
setViewOffset(fullWidth, fullHeight, x, y, width, height) | void | Sets a frustum offset for multi-window / multi-display setups |
clearViewOffset() | void | Removes the view offset from the projection matrix |
Notes
- Call
updateProjectionMatrix()after changing any frustum property. - Unlike
PerspectiveCamera,nearcan be0for orthographic cameras.
Related
- Camera
- PerspectiveCamera
PerspectiveCamera
The most common camera for 3D scenes. Uses perspective projection to mimic human vision, where objects appear smaller as they get farther away.
Signature / Usage
const camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
scene.add(camera);Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
fov | number | 50 | Vertical field of view in degrees |
aspect | number | 1 | Aspect ratio (usually canvas width / height) |
near | number | 0.1 | Near clipping plane (must be > 0) |
far | number | 2000 | Far clipping plane (must be > near) |
zoom | number | 1 | Zoom factor |
focus | number | 10 | Object distance used for stereoscopy / depth-of-field |
filmGauge | number | 35 | Film size in millimeters (used with setFocalLength) |
filmOffset | number | 0 | Horizontal off-center offset in millimeters |
view | `Object \ | null` | null |
isPerspectiveCamera | boolean (readonly) | true | Type-testing flag |
Methods
| Method | Returns | Description |
|---|---|---|
updateProjectionMatrix() | void | Must be called after any property change |
getEffectiveFOV() | number | Vertical FOV in degrees considering current zoom |
setFocalLength(focalLength) | void | Sets fov from a focal length (based on filmGauge) |
getFocalLength() | number | Returns focal length computed from fov and filmGauge |
getFilmWidth() | number | Returns film width based on filmGauge and aspect |
getFilmHeight() | number | Returns film height based on filmGauge |
getViewBounds(distance, minTarget, maxTarget) | void | Computes 2D bounds of the viewable rectangle at a given distance |
getViewSize(distance, target) | Vector2 | Returns width and height of the viewable rectangle at a distance |
setViewOffset(fullWidth, fullHeight, x, y, width, height) | void | Sets a frustum offset for multi-window / multi-display setups |
clearViewOffset() | void | Removes the view offset from the projection matrix |
Notes
- Call
updateProjectionMatrix()after changingfov,aspect,near, orfar. - When the canvas is resized, update
camera.aspectand callupdateProjectionMatrix().
Related
- Camera
- OrthographicCamera
- ArrayCamera
Cameras
| Name | Description | Path |
|---|---|---|
| Camera | Abstract base class for all cameras | Camera.md |
| PerspectiveCamera | Perspective projection camera; the most common choice for 3D scenes | PerspectiveCamera.md |
| OrthographicCamera | Orthographic projection camera; object size is independent of distance | OrthographicCamera.md |
| ArrayCamera | Array of sub-cameras for efficient multi-viewport / VR rendering | ArrayCamera.md |
| CubeCamera | Renders a cube map for real-time reflections and environment maps | CubeCamera.md |
| StereoCamera | Dual-camera setup for stereoscopic 3D rendering | StereoCamera.md |
StereoCamera
A dual-camera setup that uses two PerspectiveCamera instances for stereoscopic rendering effects such as anaglyph 3D or parallax barrier displays.
Signature / Usage
const stereoCamera = new THREE.StereoCamera();
stereoCamera.eyeSep = 0.064;
stereoCamera.update(camera); // camera is a PerspectiveCameraOptions / Props
| Name | Type | Default | Description |
|---|---|---|---|
aspect | number | 1 | Aspect ratio |
eyeSep | number | 0.064 | Eye separation distance (in world units) between left and right cameras |
cameraL | PerspectiveCamera | — | Left eye camera, added to layer 1 |
cameraR | PerspectiveCamera | — | Right eye camera, added to layer 2 |
type | string (readonly) | — | Object type identifier |
Methods
update(camera: PerspectiveCamera)
Updates the left and right sub-cameras based on the given PerspectiveCamera.
Notes
- Objects visible to the left eye must be added to layer 1; objects for the right eye to layer 2.
eyeSepaffects the perceived depth of the stereoscopic effect.
Related
- Camera
- PerspectiveCamera
ArcballControls
Camera control based on a virtual trackball interface. Cursor/finger positions are mapped onto a virtual sphere (gizmo), producing intuitive rotation. Supports full touch input, focus animation, FOV manipulation, and state serialization. Unlike OrbitControls, it does not require update() in the animation loop when animations are enabled.
Signature / Usage
import { ArcballControls } from 'three/addons/controls/ArcballControls.js';
const controls = new ArcballControls(camera, renderer.domElement, scene);
controls.addEventListener('change', () => {
renderer.render(scene, camera);
});
// No manual update() needed in animation loop
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}Constructor
new ArcballControls(camera: Camera, domElement: HTMLElement, scene?: Scene)| Parameter | Type | Description |
|---|---|---|
camera | Camera | Camera to control; must not be a child of another object unless it's the scene itself |
domElement | HTMLElement | HTML element for event listeners (default: null) |
scene | Scene | Scene rendered by camera; required to display gizmos (default: null) |
Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
target | Vector3 | (0,0,0) | Focus point of the controls |
enableRotate | boolean | true | Enable camera rotation |
enablePan | boolean | true | Enable camera panning |
enableZoom | boolean | true | Enable camera zoom |
enableAnimations | boolean | true | Enable rotation/focus animations |
enableFocus | boolean | true | Enable double-tap focus operations |
enableGizmos | boolean | true | Show/hide the arcball gizmo |
enableGrid | boolean | false | Show grid during pan (desktop only) |
dampingFactor | number | 25 | Damping inertia for animations |
wMax | number | 20 | Maximum angular velocity |
rotateSpeed | number | 1 | Rotation speed multiplier |
scaleFactor | number | 1.1 | Zoom scaling factor per step |
focusAnimationTime | number | 500 | Focus animation duration (ms) |
cursorZoom | boolean | false | Make zoom cursor-centered |
adjustNearFar | boolean | false | Auto-adjust camera near/far on zoom (perspective only) |
radiusFactor | number | 0.67 | Gizmo size relative to screen |
minDistance | number | 0 | Minimum dolly distance (PerspectiveCamera) |
maxDistance | number | Infinity | Maximum dolly distance (PerspectiveCamera) |
minZoom | number | 0 | Minimum zoom (OrthographicCamera) |
maxZoom | number | Infinity | Maximum zoom (OrthographicCamera) |
minFov | number | 5 | Minimum FOV in degrees |
maxFov | number | 90 | Maximum FOV in degrees |
mouseActions | Array | — | Configured mouse actions array |
scene | Scene | null | Scene for gizmo rendering |
Methods
Transform / State
| Method | Signature | Description |
|---|---|---|
reset | (): void | Reset to initial state |
saveState | (): void | Save current state for later reset() |
copyState | (): void | Copy current state to clipboard as JSON |
pasteState | (): void | Restore state from clipboard JSON |
Camera
| Method | Signature | Description |
|---|---|---|
setCamera | (camera: Camera): void | Set a new camera to control |
Gizmo
| Method | Signature | Description |
|---|---|---|
setGizmosVisible | (value: boolean): void | Toggle gizmo visibility |
activateGizmos | (isActive: boolean): void | Adjust gizmo visibility intensity |
setTbRadius | (value: number): void | Set gizmo radius factor |
disposeGrid | (): void | Remove grid from scene |
getRaycaster | (): Raycaster | Get internal raycaster |
Mouse Actions
// Configure a mouse action
controls.setMouseAction(
operation: 'PAN' | 'ROTATE' | 'ZOOM' | 'FOV',
mouse: 0 | 1 | 2 | 'WHEEL',
key?: 'CTRL' | 'SHIFT' | null
): boolean
// Remove a mouse action
controls.unsetMouseAction(
mouse: 0 | 1 | 2 | 'WHEEL',
key?: 'CTRL' | 'SHIFT' | null
): booleanEvents
| Event | Description |
|---|---|
change | Fires when camera is transformed |
start | Fires when interaction begins |
end | Fires when interaction finishes |
Notes
- Unlike OrbitControls,
update()does not need to be called each frame; animations run internally - The
sceneparameter is required to render the arcball gizmo - State can be serialized to clipboard via
copyState()/pasteState()(Ctrl+C/V by default) - Camera must not be a child of another object (unless that object is the scene itself)
Related
- OrbitControls
- TrackballControls
DragControls
Addon control that makes 3D objects draggable with mouse/pointer interaction. Fires events on drag start, drag, and drag end, as well as on hover.
Signature / Usage
import { DragControls } from 'three/addons/controls/DragControls.js';
const controls = new DragControls(objects, camera, renderer.domElement);
controls.addEventListener('dragstart', (event) => {
event.object.material.emissive.set(0xaaaaaa);
});
controls.addEventListener('dragend', (event) => {
event.object.material.emissive.set(0x000000);
});Constructor
new DragControls(objects: Object3D[], camera: Camera, domElement: HTMLElement)| Parameter | Type | Description |
|---|---|---|
objects | Object3D[] | Array of draggable 3D objects |
camera | Camera | Camera of the rendered scene |
domElement | HTMLElement | HTML element for event listeners (default: null) |
Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
objects | Object3D[] | — | Array of draggable 3D objects |
raycaster | Raycaster | — | Raycaster used for object detection |
recursive | boolean | true | Allow children of draggable objects to be dragged independently |
rotateSpeed | number | 1 | Rotation speed when dragging in rotate mode |
transformGroup | boolean | false | Transform the whole group instead of individual objects (requires a single group in objects) |
Events
| Event | Description |
|---|---|
dragstart | Fires when the user starts dragging an object; event.object is the target |
drag | Fires while the user is dragging; event.object is the target |
dragend | Fires when the user finishes dragging; event.object is the target |
hoveron | Fires when pointer moves onto an object or its children |
hoveroff | Fires when pointer moves off an object |
Notes
- DragControls and OrbitControls can conflict; disable OrbitControls during drag by listening to
dragstart/dragend - Set
recursive = falseto prevent child meshes from being dragged independently
Related
- TransformControls
FirstPersonControls
Alternative implementation of FlyControls providing first-person camera control with mouse-look and keyboard movement. Suitable for walk-through scenes. Requires update(delta) to be called every frame.
Signature / Usage
import { FirstPersonControls } from 'three/addons/controls/FirstPersonControls.js';
const clock = new THREE.Clock();
const controls = new FirstPersonControls(camera, renderer.domElement);
controls.movementSpeed = 10;
controls.lookSpeed = 0.1;
function animate() {
const delta = clock.getDelta();
controls.update(delta);
renderer.render(scene, camera);
}Constructor
new FirstPersonControls(object: Object3D, domElement: HTMLElement)| Parameter | Type | Description |
|---|---|---|
object | Object3D | Camera managed by the controls |
domElement | HTMLElement | HTML element for event listeners (default: null) |
Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
movementSpeed | number | 1 | Camera movement speed |
lookSpeed | number | 0.005 | Mouse-look speed |
lookVertical | boolean | true | Allow vertical camera look |
autoForward | boolean | false | Automatically move the camera forward |
constrainVertical | boolean | false | Constrain vertical look to verticalMin/verticalMax |
verticalMin | number | 0 | Lower vertical look limit (radians, 0 to π) |
verticalMax | number | 0 | Upper vertical look limit (radians, 0 to π) |
heightSpeed | boolean | false | Modulate forward speed by camera height |
heightCoef | number | 1 | Speed multiplier when height is near heightMax |
heightMin | number | 0 | Lower height boundary for speed adjustment |
heightMax | number | 1 | Upper height boundary for speed adjustment |
mouseDragOn | boolean | false | (readonly) Whether mouse button is held |
Methods
| Method | Signature | Description |
|---|---|---|
update | (delta: number): void | Advance controls by delta seconds; call every frame |
handleResize | (): void | Update internal screen size; call on window resize |
lookAt | `(x: number \ | Vector3, y?: number, z?: number): this` |
Notes
update(delta)is mandatory every frame; passclock.getDelta()for frame-rate independence- Call
handleResize()when the canvas or window is resized - For game-style first-person movement with pointer lock, consider PointerLockControls instead
Related
- FlyControls
- PointerLockControls
FlyControls
Free-form 3D camera navigation similar to fly mode in DCC tools (e.g., Blender). Unlike OrbitControls, it has no target — the camera can move and rotate freely in all directions. Requires update(delta) each frame.
Signature / Usage
import { FlyControls } from 'three/addons/controls/FlyControls.js';
const clock = new THREE.Clock();
const controls = new FlyControls(camera, renderer.domElement);
controls.movementSpeed = 10;
controls.rollSpeed = Math.PI / 24;
controls.dragToLook = true;
function animate() {
const delta = clock.getDelta();
controls.update(delta);
renderer.render(scene, camera);
}Constructor
new FlyControls(object: Object3D, domElement: HTMLElement)| Parameter | Type | Description |
|---|---|---|
object | Object3D | Camera managed by the controls |
domElement | HTMLElement | HTML element for event listeners (default: null) |
Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
movementSpeed | number | 1 | Camera movement speed |
rollSpeed | number | 0.005 | Camera rotation (roll) speed |
dragToLook | boolean | false | Require mouse drag for rotation (vs. moving mouse anywhere) |
autoForward | boolean | false | Continuously move forward after initial translation |
Events
| Event | Description |
|---|---|
change | Fires when the camera has been transformed |
Notes
update(delta)must be called every frame- No concept of a fixed target point — full 6-DOF movement
dragToLook = trueis recommended to avoid unintentional rotation
Related
- FirstPersonControls
- PointerLockControls
MapControls
Subclass of OrbitControls optimized for top-down map-style navigation. Left mouse button pans, right mouse button rotates, and screenSpacePanning is false by default so panning stays in the ground plane.
Signature / Usage
import { MapControls } from 'three/addons/controls/MapControls.js';
const controls = new MapControls(camera, renderer.domElement);
controls.enableDamping = true;
function animate() {
controls.update();
renderer.render(scene, camera);
}Input Scheme:
- Pan: Left mouse / arrow keys / one-finger touch
- Zoom: Middle mouse / mousewheel / two-finger pinch
- Orbit: Right mouse / left mouse + ctrl/meta/shift / two-finger rotate
Constructor
new MapControls(object: Object3D, domElement: HTMLElement)Inherits the same constructor parameters as OrbitControls.
Options / Props
MapControls inherits all properties from OrbitControls and overrides the following defaults:
| Name | Type | Default | Description |
|---|---|---|---|
screenSpacePanning | boolean | false | Pan orthogonal to camera.up (world plane), not screen space |
mouseButtons | Object | See below | Mouse button → action mapping |
touches | Object | See below | Touch gesture → action mapping |
// Default mouse bindings (swapped from OrbitControls)
controls.mouseButtons = {
LEFT: THREE.MOUSE.PAN,
MIDDLE: THREE.MOUSE.DOLLY,
RIGHT: THREE.MOUSE.ROTATE
};
// Default touch bindings
controls.touches = {
ONE: THREE.TOUCH.PAN,
TWO: THREE.TOUCH.DOLLY_ROTATE
};All other OrbitControls properties (enableDamping, autoRotate, minDistance, etc.) are available.
Notes
- MapControls is identical to OrbitControls except for the swapped mouse bindings and
screenSpacePanningdefault - Inherits all methods and events from OrbitControls
update()must be called in the animation loop whenenableDampingorautoRotateis enabled
Related
- OrbitControls
OrbitControls
Camera control that allows orbiting around a target point. Performs orbiting, dollying (zooming), and panning while maintaining the camera's up direction (+Y by default). The most commonly used camera control in Three.js.
Signature / Usage
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
function animate() {
controls.update(); // required when enableDamping or autoRotate is true
renderer.render(scene, camera);
}Control Scheme:
- Orbit: Left mouse / one-finger touch
- Zoom: Middle mouse / mousewheel / two-finger pinch
- Pan: Right mouse / left mouse + ctrl/meta/shift / arrow keys / two-finger touch
Constructor
new OrbitControls(object: Object3D, domElement: HTMLElement)| Parameter | Type | Description |
|---|---|---|
object | Object3D | The camera managed by the controls |
domElement | HTMLElement | HTML element for event listeners (default: null) |
Options / Props
Core
| Name | Type | Default | Description |
|---|---|---|---|
target | Vector3 | (0,0,0) | Focus point the camera orbits around |
enabled | boolean | true | Enable/disable all controls |
Rotation
| Name | Type | Default | Description |
|---|---|---|---|
enableRotate | boolean | true | Enable camera rotation |
rotateSpeed | number | 1 | Rotation speed multiplier |
minPolarAngle | number | 0 | Minimum vertical orbit angle (radians) |
maxPolarAngle | number | Math.PI | Maximum vertical orbit angle (radians) |
minAzimuthAngle | number | -Infinity | Minimum horizontal orbit angle (radians) |
maxAzimuthAngle | number | Infinity | Maximum horizontal orbit angle (radians) |
Zoom / Dolly
| Name | Type | Default | Description |
|---|---|---|---|
enableZoom | boolean | true | Enable zooming/dollying |
zoomSpeed | number | 1 | Zoom speed multiplier |
zoomToCursor | boolean | false | Zoom toward cursor position instead of target |
minDistance | number | 0 | Minimum dolly distance (PerspectiveCamera) |
maxDistance | number | Infinity | Maximum dolly distance (PerspectiveCamera) |
minZoom | number | 0 | Minimum zoom level (OrthographicCamera) |
maxZoom | number | Infinity | Maximum zoom level (OrthographicCamera) |
Pan
| Name | Type | Default | Description |
|---|---|---|---|
enablePan | boolean | true | Enable camera panning |
panSpeed | number | 1 | Pan speed multiplier |
screenSpacePanning | boolean | true | true: pan in screen space; false: pan in world plane orthogonal to camera.up |
keyPanSpeed | number | 7 | Keyboard pan speed in pixels per keypress |
keyRotateSpeed | number | 1 | Keyboard rotation speed |
Damping / Auto-rotate
| Name | Type | Default | Description |
|---|---|---|---|
enableDamping | boolean | false | Enable inertia/damping effect |
dampingFactor | number | 0.05 | Damping inertia factor (requires update() in loop) |
autoRotate | boolean | false | Automatically rotate around target |
autoRotateSpeed | number | 2 | Auto-rotate speed (2 = 30 sec/orbit at 60fps) |
Cursor / Target Constraints
| Name | Type | Default | Description |
|---|---|---|---|
cursor | Vector3 | — | Focus point for minTargetRadius/maxTargetRadius constraint |
cursorStyle | 'auto' \ | 'grab' | 'auto' |
minTargetRadius | number | 0 | Min distance of target from cursor |
maxTargetRadius | number | Infinity | Max distance of target from cursor |
Input Bindings
controls.keys = {
LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown'
};
controls.mouseButtons = {
LEFT: THREE.MOUSE.ROTATE, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN
};
controls.touches = {
ONE: THREE.TOUCH.ROTATE, TWO: THREE.TOUCH.DOLLY_PAN
};Methods
| Method | Signature | Description |
|---|---|---|
update | (deltaTime?: number): boolean | Update the controls. Must be called in the animation loop when enableDamping or autoRotate is true. Returns true if the view changed |
saveState | (): void | Save the current state; can be restored with reset() |
reset | (): void | Reset to the last saved or initial state |
getDistance | (): number | Return distance from camera to target |
getPolarAngle | (): number | Return current vertical rotation angle (radians) |
getAzimuthalAngle | (): number | Return current horizontal rotation angle (radians) |
listenToKeyEvents | (domElement: HTMLElement): void | Add key event listeners to the given DOM element |
stopListenToKeyEvents | (): void | Remove key event listeners |
rotateLeft | (angle: number): void | Programmatically rotate left by angle (radians) |
rotateUp | (angle: number): void | Programmatically rotate up by angle (radians) |
pan | (deltaX: number, deltaY: number): void | Programmatically pan by pixel delta |
dollyIn | (dollyScale: number): void | Programmatically dolly in (zoom in) |
dollyOut | (dollyScale: number): void | Programmatically dolly out (zoom out) |
dispose | (): void | Remove event listeners |
Events
| Event | Description |
|---|---|
change | Fires when the camera has been transformed |
start | Fires when an interaction begins |
end | Fires when an interaction finishes |
controls.addEventListener('change', () => renderer.render(scene, camera));Notes
update()must be called each frame whenenableDampingorautoRotateis enabled- Call
controls.update()after any manual changes to the camera's transform - MapControls is a subclass of OrbitControls with mouse buttons swapped for map-style navigation
- To restrict polar angle and prevent flipping through the pole, set
maxPolarAnglebelowMath.PI
Related
- MapControls
- TrackballControls
- ArcballControls
PointerLockControls
First-person camera control based on the browser Pointer Lock API. Captures the mouse cursor for full-screen first-person navigation, ideal for 3D games. Provides movement helpers that stay parallel to the xz-plane.
Signature / Usage
import { PointerLockControls } from 'three/addons/controls/PointerLockControls.js';
const controls = new PointerLockControls(camera, document.body);
scene.add(controls.object);
// Lock pointer on click
document.addEventListener('click', () => controls.lock());
controls.addEventListener('lock', () => { menu.style.display = 'none'; });
controls.addEventListener('unlock', () => { menu.style.display = 'block'; });
// In animation loop — move with keyboard
function animate() {
if (controls.isLocked) {
if (moveForward) controls.moveForward(speed * delta);
if (moveRight) controls.moveRight(speed * delta);
}
renderer.render(scene, camera);
}Constructor
new PointerLockControls(camera: Camera, domElement: HTMLElement)| Parameter | Type | Description |
|---|---|---|
camera | Camera | Camera managed by the controls |
domElement | HTMLElement | HTML element for event listeners (default: null) |
Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
isLocked | boolean | false | (readonly) Whether the pointer is currently locked |
pointerSpeed | number | 1 | Multiplier for pointer movement influence on camera rotation |
minPolarAngle | number | 0 | Minimum camera pitch (radians, 0 to π) |
maxPolarAngle | number | Math.PI | Maximum camera pitch (radians, 0 to π) |
Methods
| Method | Signature | Description |
|---|---|---|
lock | (unadjustedMovement?: boolean): void | Activate pointer lock. Pass true to disable OS mouse acceleration |
unlock | (): void | Exit pointer lock |
getDirection | (v: Vector3): Vector3 | Store and return the normalized camera look direction in v |
moveForward | (distance: number): void | Move camera forward/backward parallel to the xz-plane |
moveRight | (distance: number): void | Move camera left/right parallel to the xz-plane |
dispose | (): void | Remove event listeners |
Events
| Event | Description |
|---|---|
lock | Fires when pointer lock is activated |
unlock | Fires when pointer lock is deactivated |
change | Fires when the user moves the mouse |
Notes
- Pointer lock requires a user gesture (e.g., click) to activate; browsers block automatic locking
moveForwardandmoveRightmove parallel to the xz-plane, ignoring camera pitch (standard FPS behavior)- Combine with keyboard events to implement WASD movement
Related
- FirstPersonControls
- FlyControls
Controls
| Name | Description | Path |
|---|---|---|
| OrbitControls | Orbit/zoom/pan around a target point; maintains camera up direction. Most commonly used control | OrbitControls.md |
| ArcballControls | Virtual trackball control with gizmo, animations, and state serialization; no update() needed | ArcballControls.md |
| DragControls | Makes 3D objects draggable with pointer interaction; fires drag/hover events | DragControls.md |
| FirstPersonControls | First-person walk-through camera with mouse-look and keyboard movement | FirstPersonControls.md |
| FlyControls | Free-form 6-DOF fly navigation with no fixed target | FlyControls.md |
| MapControls | OrbitControls subclass with left-mouse-pan default for map-style top-down navigation | MapControls.md |
| PointerLockControls | First-person control using Pointer Lock API for game-style mouse capture | PointerLockControls.md |
| TrackballControls | Trackball rotation without maintaining camera up; full-sphere rotation | TrackballControls.md |
| TransformControls | Translate/rotate/scale objects in the viewport with a gizmo UI | TransformControls.md |
TrackballControls
Camera control similar to OrbitControls, but does not maintain a constant up direction. The camera can rotate freely through the poles without flipping, providing a true trackball-like experience. Requires update() every frame.
Signature / Usage
import { TrackballControls } from 'three/addons/controls/TrackballControls.js';
const controls = new TrackballControls(camera, renderer.domElement);
controls.rotateSpeed = 1;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
window.addEventListener('resize', () => controls.handleResize());
function animate() {
controls.update();
renderer.render(scene, camera);
}Constructor
new TrackballControls(object: Object3D, domElement: HTMLElement)| Parameter | Type | Description |
|---|---|---|
object | Object3D | Camera managed by the controls |
domElement | HTMLElement | HTML element for event listeners (default: null) |
Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
target | Vector3 | (0,0,0) | Focus point of the controls |
rotateSpeed | number | 1 | Rotation speed |
zoomSpeed | number | 1.2 | Zoom speed |
panSpeed | number | 0.3 | Pan speed |
noRotate | boolean | false | Disable rotation |
noZoom | boolean | false | Disable zooming |
noPan | boolean | false | Disable panning |
staticMoving | boolean | false | Disable damping; instant stop when input ends |
dynamicDampingFactor | number | 0.2 | Damping intensity when staticMoving is false |
minDistance | number | 0 | Minimum dolly distance (PerspectiveCamera) |
maxDistance | number | Infinity | Maximum dolly distance (PerspectiveCamera) |
minZoom | number | 0 | Minimum zoom (OrthographicCamera) |
maxZoom | number | Infinity | Maximum zoom (OrthographicCamera) |
keys | string[] | ['KeyA','KeyS','KeyD'] | Keys for orbit, zoom, pan interactions |
mouseButtons | Object | See below | Mouse button → action mapping |
screen | Object | — | (readonly) Screen properties, auto-set by handleResize() |
controls.mouseButtons = {
LEFT: THREE.MOUSE.ROTATE,
MIDDLE: THREE.MOUSE.DOLLY,
RIGHT: THREE.MOUSE.PAN
};Methods
| Method | Signature | Description |
|---|---|---|
update | (): void | Update controls; must be called every frame |
handleResize | (): void | Update internal screen info; call on window/canvas resize |
reset | (): void | Reset to initial state |
Events
| Event | Description |
|---|---|
change | Fires when the camera has been transformed |
start | Fires when interaction begins |
end | Fires when interaction finishes |
Notes
- Key difference from OrbitControls: camera
upvector is not preserved — allows full-sphere rotation without flipping update()must be called every frame (not just when damping is enabled)- Call
handleResize()whenever the window or canvas is resized to keep interactions accurate
Related
- OrbitControls
- ArcballControls
TransformControls
Addon control for translating, rotating, and scaling 3D objects directly in the viewport using an interaction model similar to DCC tools (Blender, Maya). Unlike camera controls, TransformControls transforms the attached object, not the camera.
Signature / Usage
import { TransformControls } from 'three/addons/controls/TransformControls.js';
const controls = new TransformControls(camera, renderer.domElement);
scene.add(controls.getHelper()); // add visual gizmo to scene
controls.attach(mesh); // attach object to transform
// Switch modes with keyboard
document.addEventListener('keydown', (e) => {
if (e.key === 't') controls.setMode('translate');
if (e.key === 'r') controls.setMode('rotate');
if (e.key === 's') controls.setMode('scale');
});
controls.addEventListener('dragging-changed', (e) => {
orbitControls.enabled = !e.value; // disable orbit while dragging
});Constructor
new TransformControls(camera: Camera, domElement: HTMLElement)| Parameter | Type | Description |
|---|---|---|
camera | Camera | Camera of the rendered scene |
domElement | HTMLElement | HTML element for event listeners (default: null) |
Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
camera | Camera | — | Camera of the rendered scene |
mode | 'translate' \ | 'rotate' \ | 'scale' |
space | 'world' \ | 'local' | 'world' |
size | number | 1 | Size of the helper gizmo UI |
axis | string | — | Currently active transformation axis |
dragging | boolean | false | (readonly) Whether dragging is in progress |
translationSnap | number | null | Translation snap increment in world units |
rotationSnap | number | null | Rotation snap increment in radians |
scaleSnap | number | null | Scale snap increment |
minX | number | -Infinity | Minimum allowed X position during translation |
maxX | number | Infinity | Maximum allowed X position during translation |
minY | number | -Infinity | Minimum allowed Y position during translation |
maxY | number | Infinity | Maximum allowed Y position during translation |
minZ | number | -Infinity | Minimum allowed Z position during translation |
maxZ | number | Infinity | Maximum allowed Z position during translation |
showX | boolean | true | Show X-axis gizmo |
showY | boolean | true | Show Y-axis gizmo |
showZ | boolean | true | Show Z-axis gizmo |
showXY | boolean | true | Show XY-plane gizmo |
showXZ | boolean | true | Show XZ-plane gizmo |
showYZ | boolean | true | Show YZ-plane gizmo |
Methods
| Method | Signature | Description |
|---|---|---|
attach | (object: Object3D): this | Set the object to transform and show gizmo |
detach | (): this | Remove the current object and hide gizmo |
getHelper | (): TransformControlsRoot | Return the visual gizmo — must be added to the scene |
setMode | `(mode: 'translate' \ | 'rotate' \ |
getMode | (): string | Get current transformation mode |
setSpace | `(space: 'world' \ | 'local'): void` |
setSize | (size: number): void | Set gizmo UI size |
setTranslationSnap | (snap: number): void | Set translation snap increment |
setRotationSnap | (snap: number): void | Set rotation snap increment |
setScaleSnap | (snap: number): void | Set scale snap increment |
setColors | (xAxis, yAxis, zAxis, active): void | Set gizmo axis colors |
getRaycaster | (): Raycaster | Return internal raycaster (shared across instances) |
reset | (): void | Reset object to state at start of current transform |
dispose | (): void | Remove event listeners |
Events
| Event | Description |
|---|---|
change | Fires on any change to the controlled object or gizmo properties |
mouseDown | Fires when a pointer becomes active |
mouseUp | Fires when a pointer is released |
objectChange | Fires when the controlled 3D object's transform changes |
dragging-changed | Fires with event.value boolean when dragging starts/stops |
Notes
getHelper()returns the visual gizmo object — it must be added to the scene to be visible- The attached object must be part of the scene graph
- Disable other controls (e.g., OrbitControls) during drag by listening to
dragging-changed - Property changes emit
"[propertyname]-changed"events in addition tochange - The internal raycaster is shared across all TransformControls instances
Related
- DragControls
BufferAttribute
Stores attribute data (vertex positions, face indices, normals, colors, UVs, or custom attributes) associated with a BufferGeometry for efficient GPU transmission.
Signature / Usage
const positions = new Float32Array([0, 0, 0, 1, 0, 0, 1, 1, 0]);
const attr = new THREE.BufferAttribute(positions, 3);
geometry.setAttribute('position', attr);
// Update data
positions[0] = 0.5;
attr.needsUpdate = true;Constructor
new BufferAttribute(array: TypedArray, itemSize: number, normalized?: boolean)| Parameter | Type | Description |
|---|---|---|
array | TypedArray | Typed array holding attribute data |
itemSize | number | Number of values per vertex (e.g., 3 for position, 2 for UV) |
normalized | boolean | Map integer data to float range. Default: false |
Options / Props
| Name | Type | Description |
|---|---|---|
array | TypedArray | The underlying typed array |
count | number (readonly) | array.length / itemSize |
gpuType | FloatType \ | IntType |
id | number (readonly) | Unique identifier |
isBufferAttribute | boolean (readonly) | Type flag, always true |
itemSize | number | Values per vertex |
name | string | Attribute name |
needsUpdate | boolean | Set true to trigger GPU re-upload |
normalized | boolean | Whether integer data is normalized |
updateRanges | Array | Partial update ranges |
usage | Usage constant | Buffer usage hint. Default: StaticDrawUsage |
version | number | Increments each time needsUpdate is set to true |
Methods
Data access: getX/Y/Z/W(index), setX/Y/Z/W(index, value), setXY, setXYZ, setXYZW, getComponent, setComponent, set(value, offset), copyAt(i1, attr, i2), copyArray(array)
Transforms: applyMatrix3(m), applyMatrix4(m), applyNormalMatrix(m), transformDirection(m)
Update management: addUpdateRange(start, count), clearUpdateRanges(), setUsage(value)
Utilities: clone(), copy(source), onUpload(callback), dispose() (WebGPURenderer only), toJSON()
Notes
- Set
needsUpdate = trueafter modifyingarrayto sync with GPU. usagecannot be changed after initial GPU upload; create a new instance instead.- For partial updates of large buffers, use
addUpdateRange(). - Use typed convenience subclasses (
Float32BufferAttribute,Uint16BufferAttribute, etc.) when creating from plain arrays — see TypedBufferAttributes.
Related
- BufferGeometry
- InterleavedBuffer
- InterleavedBufferAttribute
- TypedBufferAttributes
BufferGeometry
Represents mesh, line, or point geometry by storing vertex positions, indices, normals, colors, UVs, and custom attributes in typed-array buffers. More efficient than the legacy Geometry because data is passed directly to the GPU.
Signature / Usage
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array([
-1, -1, 1,
1, -1, 1,
1, 1, 1,
]);
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: 0xff0000 }));Constructor
new BufferGeometry()Options / Props
| Name | Type | Description |
|---|---|---|
attributes | Object | Dictionary of BufferAttributes; use setAttribute/getAttribute |
boundingBox | Box3 \ | null |
boundingSphere | Sphere \ | null |
drawRange | Object | { start, count } — use setDrawRange() |
groups | Array | Material groups; use addGroup()/clearGroups() |
id | number (readonly) | Unique ID |
index | BufferAttribute \ | null |
indirect | BufferAttribute \ | null |
isBufferGeometry | boolean (readonly) | Type flag |
morphAttributes | Object | Morph target attribute dictionary |
morphTargetsRelative | boolean | Treat morphs as relative offsets. Default: false |
name | string | Geometry name |
userData | Object | Custom data storage |
uuid | string (readonly) | UUID |
Methods
Attribute management: setAttribute(name, attr), getAttribute(name), deleteAttribute(name), hasAttribute(name)
Computation: computeBoundingBox(), computeBoundingSphere(), computeVertexNormals(), computeTangents(), normalizeNormals()
Transforms: applyMatrix4(m), applyQuaternion(q), rotateX/Y/Z(angle), scale(x,y,z), translate(x,y,z), center(), lookAt(vector)
Indexing & groups: setIndex(index), getIndex(), setDrawRange(start, count), addGroup(start, count, materialIndex), clearGroups(), toNonIndexed()
Utilities: setFromPoints(points), clone(), copy(source), toJSON(), dispose()
Notes
boundingBoxandboundingSpherearenulluntil explicitly computed.- Each vertex in non-indexed geometry must be duplicated if shared by multiple triangles.
- Every vertex/index must belong to exactly one group when using multi-material rendering.
- Morph attribute data cannot change after first render;
dispose()and recreate the geometry. indirect/indirectOffsetare WebGPURenderer-only.- Call
dispose()when geometry is no longer needed to free GPU memory.
Related
- BufferAttribute
- InstancedBufferGeometry
Clock
Tracks elapsed and per-frame delta time for use in animation loops.
Deprecated note: The autoStart constructor parameter is deprecated since r183. Consider using Timer for new projects.Signature / Usage
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta(); // seconds since last call
const elapsed = clock.getElapsedTime(); // total seconds
mesh.rotation.y += delta;
renderer.render(scene, camera);
}Constructor
new Clock(autoStart?: boolean)| Parameter | Type | Description |
|---|---|---|
autoStart | boolean | Start automatically on first getDelta() call. Default: true. Deprecated since r183. |
Options / Props
| Name | Type | Description |
|---|---|---|
autoStart | boolean | Whether to start on first getDelta() |
elapsedTime | number | Accumulated running time in seconds |
oldTime | number | Timestamp of last start() / getDelta() / getElapsedTime() call |
running | boolean | Whether clock is currently running |
startTime | number | Timestamp when start() was last called |
Methods
| Method | Returns | Description |
|---|---|---|
getDelta() | number | Seconds elapsed since last call |
getElapsedTime() | number | Total seconds since clock started |
start() | void | Starts the clock |
stop() | void | Stops the clock |
Notes
- Each call to
getDelta()updates the internal reference time, so calling it multiple times per frame yields different values. Use Timer to avoid this issue.
Related
- Timer
EventDispatcher
Provides a standard event system for custom JavaScript classes. Most Three.js classes (including Object3D) extend EventDispatcher.
Signature / Usage
class Car extends THREE.EventDispatcher {
start() {
this.dispatchEvent({ type: 'start', message: 'vroom!' });
}
}
const car = new Car();
car.addEventListener('start', (event) => {
console.log(event.message);
});
car.start();Constructor
new EventDispatcher()Methods
| Method | Signature | Description |
|---|---|---|
addEventListener | (type: string, listener: Function): void | Register a listener for an event type |
removeEventListener | (type: string, listener: Function): void | Remove a registered listener |
hasEventListener | (type: string, listener: Function): boolean | Check if a listener is registered |
dispatchEvent | (event: Object): void | Fire an event; event.type must be set |
Notes
eventpassed todispatchEventmust have atypestring property. Any additional properties are forwarded to listeners.- Use
extends EventDispatcherpattern; do not instantiate directly unless building a standalone event emitter.
GLBufferAttribute
A buffer attribute that wraps a raw WebGL WebGLBuffer (VBO) directly, bypassing Three.js's internal VBO management. Primarily used for GPGPU workflows where a compute pass produces a VBO consumed by the renderer.
Compatibility: WebGLRenderer only.
Signature / Usage
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);
const attr = new THREE.GLBufferAttribute(buffer, gl.FLOAT, 3, 4, vertexCount);
geometry.setAttribute('position', attr);Constructor
new GLBufferAttribute(buffer, type, itemSize, elementSize, count, normalized?)| Parameter | Type | Description |
|---|---|---|
buffer | WebGLBuffer | The native WebGL buffer |
type | number | Native GL data type (e.g., gl.FLOAT) |
itemSize | number | Number of components per vertex |
elementSize | number | Byte size of one element (e.g., 4 for gl.FLOAT) |
count | number | Expected number of vertices in the VBO |
normalized | boolean | Whether data is normalized. Default: false |
Options / Props
| Name | Type | Description |
|---|---|---|
buffer | WebGLBuffer | The underlying native buffer |
count | number | Expected vertex count |
elementSize | number | Byte size per element |
isGLBufferAttribute | boolean (readonly) | Type flag |
itemSize | number | Components per vertex |
name | string | Attribute name |
needsUpdate | boolean | Flag GPU re-upload |
normalized | boolean | Whether data is normalized |
type | number | Native GL data type |
version | number | Increments on needsUpdate |
Methods
| Method | Description |
|---|---|
setBuffer(buffer) | Replace the underlying WebGL buffer |
setCount(count) | Update the expected vertex count |
setItemSize(itemSize) | Update the item size |
setType(type, elementSize) | Update the native type and element byte size |
Notes
- The renderer does not create a VBO for this attribute; it uses the one you provide.
- Use
setBuffer()to swap the VBO after a GPGPU computation completes.
Related
- BufferAttribute
InstancedBufferAttribute
An instanced version of BufferAttribute. Holds per-instance data for instanced rendering; each value is used for one or more consecutive instances rather than one per vertex.
Extends: BufferAttribute
Signature / Usage
const instanceColors = new THREE.InstancedBufferAttribute(
new Float32Array(instanceCount * 3), 3
);
// Set color for each instance
for (let i = 0; i < instanceCount; i++) {
instanceColors.setXYZ(i, Math.random(), Math.random(), Math.random());
}
geometry.setAttribute('instanceColor', instanceColors);Constructor
new InstancedBufferAttribute(array, itemSize, normalized?, meshPerAttribute?)| Parameter | Type | Description |
|---|---|---|
array | TypedArray | Data array |
itemSize | number | Components per instance |
normalized | boolean | Normalize integer data. Default: false |
meshPerAttribute | number | How many consecutive instances share this value. Default: 1 |
Options / Props
| Name | Type | Description |
|---|---|---|
isInstancedBufferAttribute | boolean (readonly) | Type flag |
meshPerAttribute | number | Number of instances each value is repeated for |
All other properties are inherited from BufferAttribute.
Notes
- Used with
InstancedBufferGeometryor directly on aBufferGeometryfor instance-level attributes. meshPerAttribute = 2means each attribute value spans two consecutive instances.
Related
- BufferAttribute
- InstancedBufferGeometry
- InstancedInterleavedBuffer
InstancedBufferGeometry
An instanced version of BufferGeometry for rendering multiple copies of the same geometry. Add per-instance attributes via InstancedBufferAttribute.
Extends: BufferGeometry
Signature / Usage
const geometry = new THREE.InstancedBufferGeometry();
geometry.instanceCount = 100;
// Copy index and base attributes from a template geometry
geometry.setIndex(baseGeometry.getIndex());
geometry.setAttribute('position', baseGeometry.getAttribute('position'));
// Per-instance offset attribute
const offsets = new THREE.InstancedBufferAttribute(
new Float32Array(100 * 3), 3
);
geometry.setAttribute('instanceOffset', offsets);Constructor
new InstancedBufferGeometry()Options / Props
| Name | Type | Description |
|---|---|---|
instanceCount | number | Number of instances to render. Default: Infinity |
isInstancedBufferGeometry | boolean (readonly) | Type flag |
All other properties are inherited from BufferGeometry.
Notes
- Set
instanceCountto limit rendered instances below the total data count. - Inherits all
BufferGeometrymethods (setAttribute,computeBoundingBox,dispose, etc.).
Related
- BufferGeometry
- InstancedBufferAttribute
InstancedInterleavedBuffer
An instanced version of InterleavedBuffer. Holds interleaved per-instance data; each value block repeats across meshPerAttribute consecutive instances.
Extends: InterleavedBuffer
Constructor
new InstancedInterleavedBuffer(array, stride, meshPerAttribute?)| Parameter | Type | Description |
|---|---|---|
array | TypedArray | Typed array with a shared buffer storing attribute data |
stride | number | Number of typed-array elements per vertex |
meshPerAttribute | number | How many consecutive instances share each value. Default: 1 |
Options / Props
| Name | Type | Description |
|---|---|---|
isInstancedInterleavedBuffer | boolean (readonly) | Type flag |
meshPerAttribute | number | Instance repetition count per value |
All other properties are inherited from InterleavedBuffer.
Related
- InterleavedBuffer
- InstancedBufferAttribute
InterleavedBuffer
Stores multiple vertex attributes (position, normal, UV, color, etc.) packed into a single typed array. Reduces memory overhead and can improve GPU cache performance compared to separate buffers.
Signature / Usage
// Interleaved: position (3 floats) + uv (2 floats) per vertex = stride 5
const data = new Float32Array([
// x, y, z, u, v
-1, -1, 0, 0, 0,
1, -1, 0, 1, 0,
1, 1, 0, 1, 1,
]);
const interleavedBuffer = new THREE.InterleavedBuffer(data, 5);
geometry.setAttribute('position',
new THREE.InterleavedBufferAttribute(interleavedBuffer, 3, 0));
geometry.setAttribute('uv',
new THREE.InterleavedBufferAttribute(interleavedBuffer, 2, 3));Constructor
new InterleavedBuffer(array: TypedArray, stride: number)| Parameter | Type | Description |
|---|---|---|
array | TypedArray | Typed array holding all interleaved attribute data |
stride | number | Number of typed-array elements per vertex |
Options / Props
| Name | Type | Description |
|---|---|---|
array | TypedArray | The shared data array |
count | number (readonly) | Total element count |
isInterleavedBuffer | boolean (readonly) | Type flag |
needsUpdate | boolean | Set true to trigger GPU re-upload |
stride | number | Elements per vertex |
updateRanges | Array | Partial update ranges |
usage | Usage constant | Buffer usage hint. Default: StaticDrawUsage |
uuid | string (readonly) | UUID |
version | number | Increments on needsUpdate |
Methods
| Method | Description |
|---|---|
addUpdateRange(start, count) | Mark a range for partial GPU update |
clearUpdateRanges() | Clear all update ranges |
clone(data) | Return a cloned instance |
copy(source) | Copy values from another InterleavedBuffer |
copyAt(i1, buffer, i2) | Copy a vertex block from another buffer |
onUpload(callback) | Callback after GPU upload |
set(value, offset) | Set array data at offset |
setUsage(value) | Set usage hint (cannot change after initial upload) |
toJSON(data) | Serialize to JSON |
Notes
usagecannot be changed after the buffer has been uploaded to the GPU.- Pair with
InterleavedBufferAttributeto expose individual attributes from the shared buffer.
Related
- InterleavedBufferAttribute
- InstancedInterleavedBuffer
InterleavedBufferAttribute
Exposes a slice of an InterleavedBuffer as a named vertex attribute. Multiple InterleavedBufferAttribute instances share one InterleavedBuffer via different offsets.
Signature / Usage
const buf = new THREE.InterleavedBuffer(data, 5); // stride 5
geometry.setAttribute('position',
new THREE.InterleavedBufferAttribute(buf, 3, 0)); // 3 components at offset 0
geometry.setAttribute('uv',
new THREE.InterleavedBufferAttribute(buf, 2, 3)); // 2 components at offset 3Constructor
new InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized?)| Parameter | Type | Description |
|---|---|---|
interleavedBuffer | InterleavedBuffer | The shared buffer |
itemSize | number | Number of components |
offset | number | Byte offset into the buffer stride |
normalized | boolean | Normalize integer data. Default: false |
Options / Props
| Name | Type | Description |
|---|---|---|
array | TypedArray | The underlying data array |
count | number (readonly) | Item count |
data | InterleavedBuffer | The shared interleaved buffer |
isInterleavedBufferAttribute | boolean (readonly) | Type flag |
itemSize | number | Components per vertex |
name | string | Attribute name |
needsUpdate | boolean | Flag GPU re-upload |
normalized | boolean | Whether data is normalized |
offset | number | Offset into the buffer stride |
Methods
Component access: getComponent(index, component), getX/Y/Z/W(index)
Component setting: setComponent(index, component, value), setX/Y/Z/W, setXY, setXYZ, setXYZW
Transforms: applyMatrix4(m), applyNormalMatrix(m), transformDirection(m) (all require itemSize = 3)
Utilities: clone(data?) — de-interleaves to a plain BufferAttribute if no data object is passed; toJSON(data?)
Related
- InterleavedBuffer
- BufferAttribute
Layers
Controls which of 32 layers (0–31) an object or camera belongs to using a bitmask. An object is visible to a camera only when they share at least one layer.
All Object3D instances expose a layers property of this type.
Signature / Usage
// Camera: see only layers 0 and 1
camera.layers.enable(1);
// Object: place on layer 1 only
mesh.layers.set(1);
// Object: visible on both layer 0 and 2
mesh.layers.enable(0);
mesh.layers.enable(2);Constructor
new Layers()Initializes with membership set to layer 0 only.
Options / Props
| Name | Type | Description |
|---|---|---|
mask | number | Bitmask of active layers |
Methods
| Method | Returns | Description |
|---|---|---|
set(layer) | void | Set membership to layer only (clears all others) |
enable(layer) | void | Add membership of layer |
enableAll() | void | Add membership to all 32 layers |
disable(layer) | void | Remove membership of layer |
disableAll() | void | Remove membership from all layers |
toggle(layer) | void | Toggle membership of layer |
isEnabled(layer) | boolean | true if layer is enabled |
test(layers) | boolean | true if this and layers share at least one layer |
Notes
- Layers are 0-indexed; valid range is
0to31. - The default state (layer 0 only) means objects and cameras are always visible to each other unless layers are explicitly changed.
Raycaster.layersuses the same mechanism to filter which objects are tested.
Related
- Object3D
- Raycaster
Object3D
Base class for most Three.js scene objects. Provides position, rotation, scale, hierarchy management, traversal, and raycasting hooks. Extends EventDispatcher.
Signature / Usage
const obj = new THREE.Object3D();
obj.position.set(1, 2, 3);
obj.rotation.y = Math.PI / 4;
obj.scale.set(2, 2, 2);
scene.add(obj);
// Hierarchy
const child = new THREE.Object3D();
obj.add(child);
// Traverse all descendants
obj.traverse((node) => console.log(node.name));Constructor
new Object3D()Options / Props
Transform
| Name | Type | Default | Description |
|---|---|---|---|
position | Vector3 | (0,0,0) | Local position |
rotation | Euler | (0,0,0) | Local rotation in radians |
quaternion | Quaternion | — | Local rotation as quaternion (synced with rotation) |
scale | Vector3 | (1,1,1) | Local scale |
up | Vector3 | (0,1,0) | Up direction for lookAt() |
pivot | Vector3 \ | null | null |
Matrices
| Name | Type | Description |
|---|---|---|
matrix | Matrix4 | Local transform matrix |
matrixWorld | Matrix4 | World transform matrix |
modelViewMatrix | Matrix4 | Model-view matrix (set by renderer) |
normalMatrix | Matrix3 | Normal matrix (set by renderer) |
matrixAutoUpdate | boolean | Auto-recompute local matrix. Default: true |
matrixWorldAutoUpdate | boolean | Auto-recompute world matrix. Default: true |
matrixWorldNeedsUpdate | boolean | Force world matrix update next frame |
Hierarchy
| Name | Type | Description |
|---|---|---|
parent | Object3D \ | null |
children | Object3D[] | Array of child objects |
Rendering
| Name | Type | Default | Description |
|---|---|---|---|
visible | boolean | true | Render this object |
castShadow | boolean | false | Contribute to shadow maps |
receiveShadow | boolean | false | Receive shadows |
renderOrder | number | 0 | Override draw order |
frustumCulled | boolean | true | Skip if outside view frustum |
layers | Layers | layer 0 | Layer membership |
static | boolean | false | Mark as static for optimization (WebGPURenderer) |
Metadata
| Name | Type | Description |
|---|---|---|
id | number (readonly) | Unique numeric ID |
uuid | string (readonly) | UUID |
name | string | Human-readable name |
type | string (readonly) | Type string for serialization |
isObject3D | boolean (readonly) | Type flag |
animations | AnimationClip[] | Attached animation clips |
userData | Object | Custom data storage |
Static Defaults
| Name | Type | Default |
|---|---|---|
Object3D.DEFAULT_UP | Vector3 | (0,1,0) |
Object3D.DEFAULT_MATRIX_AUTO_UPDATE | boolean | true |
Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE | boolean | true |
Methods
Hierarchy
add(...objects) // Add child(ren)
remove(...objects) // Remove child(ren)
attach(object) // Attach while preserving world transform
removeFromParent() // Remove self from parent
clear() // Remove all childrenPosition / Rotation / Scale
lookAt(x, y, z) // or lookAt(vector3)
translateX/Y/Z(distance)
translateOnAxis(axis, distance)
rotateX/Y/Z(angle)
rotateOnAxis(axis, angle) // local axis
rotateOnWorldAxis(axis, angle)
setRotationFromEuler(euler)
setRotationFromQuaternion(q)
setRotationFromAxisAngle(axis, angle)
setRotationFromMatrix(m)
applyMatrix4(matrix)
applyQuaternion(q)World Space
getWorldPosition(target: Vector3): Vector3
getWorldQuaternion(target: Quaternion): Quaternion
getWorldScale(target: Vector3): Vector3
getWorldDirection(target: Vector3): Vector3
localToWorld(vector: Vector3): Vector3
worldToLocal(vector: Vector3): Vector3Matrix Updates
updateMatrix()
updateMatrixWorld(force?)
updateWorldMatrix(updateParents, updateChildren)Search
getObjectById(id): Object3D | undefined
getObjectByName(name): Object3D | undefined
getObjectByProperty(property, value): Object3D | undefined
getObjectsByProperty(property, value, result?): Object3D[]Traversal
traverse(callback) // All descendants
traverseVisible(callback) // Visible descendants only
traverseAncestors(callback)Clone / Copy / Serialize
clone(recursive?: boolean): Object3D
copy(source, recursive?: boolean): this
toJSON(meta?): ObjectRender Callbacks
onBeforeRender(renderer, scene, camera, geometry, material, group)
onAfterRender(renderer, scene, camera, geometry, material, group)
onBeforeShadow(renderer, scene, camera, shadowCamera, geometry, depthMaterial, group)
onAfterShadow(renderer, scene, camera, shadowCamera, geometry, depthMaterial, group)Events
| Event | Fires when |
|---|---|
added | Object is added to a parent |
removed | Object is removed from parent |
childadded | A child is added |
childremoved | A child is removed |
Notes
rotationandquaternionare kept in sync automatically.- Use
Object3D.rotation/position/scalefor real-time transforms instead ofBufferGeometry.rotateXetc., which bake transforms into vertex data. - Setting
matrixAutoUpdate = falseand callingupdateMatrix()manually improves performance for static objects.
Related
- EventDispatcher
- Layers
- Raycaster
Raycaster
Performs raycasting to determine which 3D objects intersect a ray. Primarily used for mouse/pointer picking.
Signature / Usage
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
window.addEventListener('pointermove', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
});
// In render loop
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
console.log('Hit:', intersects[0].object.name);
}Constructor
new Raycaster(origin?, direction?, near?, far?)| Parameter | Type | Default | Description |
|---|---|---|---|
origin | Vector3 | — | Ray origin |
direction | Vector3 | — | Normalized ray direction |
near | number | 0 | Minimum hit distance (non-negative) |
far | number | Infinity | Maximum hit distance |
Options / Props
| Name | Type | Description |
|---|---|---|
camera | Camera \ | null |
far | number | Maximum distance for results |
near | number | Minimum distance for results |
ray | Ray | The underlying ray |
layers | Layers | Filter which objects are tested |
params | Object | Per-type thresholds: { Line: { threshold }, Points: { threshold }, ... } |
Methods
| Method | Description |
|---|---|
set(origin, direction) | Update ray origin and direction |
setFromCamera(coords, camera) | Build ray from NDC mouse coords and camera |
setFromXRController(controller) | Build ray from a WebXR controller |
intersectObject(object, recursive?, intersects?) | Test one object; returns sorted Intersection[] |
intersectObjects(objects, recursive?, intersects?) | Test multiple objects; returns sorted Intersection[] |
Intersection Object
{
distance: number, // Distance from ray origin
distanceToRay?: number, // Nearest ray distance (Points only)
point: Vector3, // World-space intersection point
face: Object | null, // Intersected face
faceIndex: number, // Face index
object: Object3D, // The hit object
uv: Vector2, // UV at intersection
uv1: Vector2, // Secondary UV
normal: Vector3, // Interpolated normal
instanceId?: number // InstancedMesh instance index
}Notes
- Results are sorted nearest-first;
intersects[0]is the closest hit. - Mesh faces must point toward the ray origin. Use
Material.side = THREE.DoubleSideto hit back faces. - Set
raycaster.layersto match object layers to ignore hidden objects. params.Line.thresholdandparams.Points.thresholdset hit proximity distance for non-mesh objects.
Related
- Layers
- Object3D
Core
| Name | Description | Path |
|---|---|---|
| BufferAttribute | Stores typed vertex attribute data (positions, normals, UVs, etc.) for GPU-efficient geometry | BufferAttribute.md |
| BufferGeometry | Stores geometry as typed buffers; base for all mesh/line/point geometry | BufferGeometry.md |
| Clock | Tracks elapsed time and per-frame delta for animations | Clock.md |
| EventDispatcher | Base event system; extended by most Three.js classes | EventDispatcher.md |
| GLBufferAttribute | Wraps a raw WebGL VBO directly; for GPGPU workflows (WebGLRenderer only) | GLBufferAttribute.md |
| InstancedBufferAttribute | Per-instance BufferAttribute for instanced rendering | InstancedBufferAttribute.md |
| InstancedBufferGeometry | BufferGeometry variant for instanced rendering | InstancedBufferGeometry.md |
| InstancedInterleavedBuffer | Instanced variant of InterleavedBuffer | InstancedInterleavedBuffer.md |
| InterleavedBuffer | Stores multiple vertex attributes in a single typed array (interleaved layout) | InterleavedBuffer.md |
| InterleavedBufferAttribute | Exposes a named attribute slice from an InterleavedBuffer | InterleavedBufferAttribute.md |
| Layers | Bitmask-based layer system controlling visibility and raycasting | Layers.md |
| Object3D | Base class for all scene objects; position, rotation, scale, hierarchy | Object3D.md |
| Raycaster | Casts a ray into the scene for mouse picking and intersection tests | Raycaster.md |
| RenderTarget | Off-screen render buffer whose texture can be used in subsequent passes | RenderTarget.md |
| RenderTarget3D | RenderTarget backed by a Data3DTexture for volumetric rendering | RenderTarget3D.md |
| Timer | Improved Clock with stable per-frame delta and Page Visibility API support | Timer.md |
| TypedBufferAttributes | Typed convenience subclasses of BufferAttribute (Float32, Uint16, etc.) | TypedBufferAttributes.md |
| Uniform | Single shader uniform value for use with ShaderMaterial | Uniform.md |
| UniformsGroup | Manages multiple uniforms as a single GPU Uniform Buffer Object (UBO) | UniformsGroup.md |
RenderTarget
An off-screen render buffer. The renderer draws a scene into this target instead of the canvas, making the result available as a texture for post-processing or other effects.
Signature / Usage
const renderTarget = new THREE.RenderTarget(512, 512, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
});
// Render scene into target
renderer.setRenderTarget(renderTarget);
renderer.render(scene, camera);
renderer.setRenderTarget(null);
// Use the result as a texture
material.map = renderTarget.texture;Constructor
new RenderTarget(width?, height?, options?)| Parameter | Type | Default | Description |
|---|---|---|---|
width | number | 1 | Width in pixels |
height | number | 1 | Height in pixels |
options | Object | — | Configuration (see below) |
Options
| Name | Type | Default | Description |
|---|---|---|---|
depthBuffer | boolean | true | Allocate depth buffer |
stencilBuffer | boolean | false | Allocate stencil buffer |
samples | number | 0 | MSAA sample count (0 = no MSAA) |
magFilter | number | LinearFilter | Texture magnification filter |
minFilter | number | LinearFilter | Texture minification filter |
format | number | RGBAFormat | Texture format |
type | number | UnsignedByteType | Texture data type |
wrapS/T | number | ClampToEdgeWrapping | Texture wrap modes |
colorSpace | string | NoColorSpace | Color space |
depthTexture | DepthTexture | null | Use texture for depth instead of renderbuffer |
count | number | 1 | Number of color attachments (MRT) |
multiview | boolean | false | Enable multiview rendering |
Options / Props
| Name | Type | Description |
|---|---|---|
width | number | Width in pixels |
height | number | Height in pixels |
depth | number | Depth (3D targets). Default: 1 |
texture | Texture | Default color attachment |
textures | Texture[] | All color attachments (MRT) |
depthTexture | DepthTexture \ | null |
depthBuffer | boolean | Whether depth buffer is allocated |
stencilBuffer | boolean | Whether stencil buffer is allocated |
samples | number | MSAA sample count |
viewport | Vector4 | Render viewport |
scissor | Vector4 | Scissor region |
scissorTest | boolean | Enable scissor test |
isRenderTarget | boolean (readonly) | Type flag |
Methods
| Method | Description |
|---|---|
setSize(width, height, depth?) | Resize the render target |
clone() | Return a copy of this target |
copy(source) | Copy settings from another target |
dispose() | Free GPU resources; fires dispose event |
Notes
- Call
dispose()when the target is no longer needed to free GPU memory. - For cube-map targets use
WebGLCubeRenderTarget; for 3D textures useRenderTarget3D.
Related
- RenderTarget3D
RenderTarget3D
A render target backed by a 3D texture (Data3DTexture). Use when rendering into a 3D volume texture.
Extends: RenderTarget
Constructor
new RenderTarget3D(width?, height?, depth?, options?)| Parameter | Type | Default | Description |
|---|---|---|---|
width | number | 1 | Width in pixels |
height | number | 1 | Height in pixels |
depth | number | 1 | Depth (number of slices) |
options | Object | — | Same options as RenderTarget |
Options / Props
| Name | Type | Description |
|---|---|---|
isRenderTarget3D | boolean (readonly) | Type flag |
texture | Data3DTexture | Overrides RenderTarget.texture with a Data3DTexture |
All other properties are inherited from RenderTarget.
Notes
- Inherits all
RenderTargetmethods:setSize(),clone(),copy(),dispose().
Related
- RenderTarget
Timer
An improved alternative to Clock that separates state update from value retrieval, and supports the Page Visibility API to avoid large delta spikes when the tab is inactive.
Signature / Usage
const timer = new THREE.Timer();
timer.connect(document); // opt-in to Page Visibility API
function animate(timestamp) {
requestAnimationFrame(animate);
timer.update(timestamp); // call once per frame first
const delta = timer.getDelta(); // consistent value per frame
const elapsed = timer.getElapsed();
mesh.rotation.y += delta;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);Constructor
new Timer()Methods
| Method | Signature | Description |
|---|---|---|
update | (timestamp?: number): Timer | Update internal state. Call once per frame before getDelta()/getElapsed(). Uses performance.now() if no timestamp is provided. |
getDelta | (): number | Time delta in seconds since last update() |
getElapsed | (): number | Total elapsed time in seconds |
getTimescale | (): number | Current timescale multiplier |
setTimescale | (timescale: number): Timer | Scale time delta (e.g., 0.5 for slow motion) |
reset | (): Timer | Reset time computation for current step |
connect | (document: Document): void | Enable Page Visibility API integration |
disconnect | (): void | Disconnect from DOM |
dispose | (): void | Free all resources |
Notes
- Unlike
Clock.getDelta(), callinggetDelta()multiple times per frame always returns the same value after a singleupdate(). connect(document)prevents large delta jumps when the user switches tabs.- Pass
timestampfromrequestAnimationFrametoupdate()for the most accurate timing.
Related
- Clock
Typed BufferAttribute Subclasses
Convenience subclasses of BufferAttribute for specific numeric types. Each wraps a typed array of the corresponding kind, inheriting all BufferAttribute properties and methods.
Classes
| Class | Typed Array | Description |
|---|---|---|
Float16BufferAttribute | Uint16Array (FP16 encoded) | 16-bit float; handles conversion automatically |
Float32BufferAttribute | Float32Array | 32-bit float; most common for positions/normals |
Int8BufferAttribute | Int8Array | Signed 8-bit integer |
Int16BufferAttribute | Int16Array | Signed 16-bit integer |
Int32BufferAttribute | Int32Array | Signed 32-bit integer |
Uint8BufferAttribute | Uint8Array | Unsigned 8-bit integer |
Uint8ClampedBufferAttribute | Uint8ClampedArray | Unsigned 8-bit clamped integer |
Uint16BufferAttribute | Uint16Array | Unsigned 16-bit integer; typical for index buffers |
Uint32BufferAttribute | Uint32Array | Unsigned 32-bit integer; large index buffers |
All extend BufferAttribute.
Signature / Usage
// Float32 positions (most common)
geometry.setAttribute(
'position',
new THREE.Float32BufferAttribute([0, 0, 0, 1, 0, 0, 1, 1, 0], 3)
);
// Uint16 index buffer
geometry.setIndex(new THREE.Uint16BufferAttribute([0, 1, 2], 1));
// Float16 for memory-sensitive attributes
geometry.setAttribute(
'uv',
new THREE.Float16BufferAttribute([0, 0, 1, 0, 1, 1], 2)
);Constructor (all variants)
new Float32BufferAttribute(array, itemSize, normalized?)
new Uint16BufferAttribute(array, itemSize, normalized?)
// ... same signature for all variants| Parameter | Type | Description |
|---|---|---|
array | Typed array or plain Array | The attribute data |
itemSize | number | Components per vertex |
normalized | boolean | Normalize integer data. Default: false |
Notes
Float16BufferAttributeautomatically converts from plainArrayorUint16Arrayto FP16, working around incompleteFloat16Arraybrowser support.- Choose
Uint16BufferAttributefor index buffers with fewer than 65 536 vertices; useUint32BufferAttributefor larger meshes. - All inherited
BufferAttributeupdate semantics apply (needsUpdate,addUpdateRange, etc.).
Related
- BufferAttribute
Uniform
Represents a single global shader variable passed to ShaderMaterial shader programs.
Compatibility: WebGLRenderer with ShaderMaterial only.Signature / Usage
const material = new THREE.ShaderMaterial({
uniforms: {
time: new THREE.Uniform(0.0),
resolution: new THREE.Uniform(new THREE.Vector2(800, 600)),
},
vertexShader: `...`,
fragmentShader: `...`,
});
// Update each frame
material.uniforms.time.value += delta;Constructor
new Uniform(value: any)Options / Props
| Name | Type | Description |
|---|---|---|
value | any | The uniform's current value |
name | string | Uniform name |
boundary | number | STD140 alignment boundary (set by derived types) |
index | number | Position index in UniformsGroup array |
itemSize | number | Item size (set by derived types) |
offset | number | Byte offset in UniformsGroup buffer |
Methods
| Method | Returns | Description |
|---|---|---|
clone() | Uniform | Deep clone (calls value.clone() if available) |
getValue() | any | Returns value |
setValue(value) | void | Sets value |
Notes
- The shorthand object literal
{ value: ... }is also accepted byShaderMaterial.uniforms;new Uniform(...)is equivalent but more explicit.
Related
- UniformsGroup
UniformsGroup
Manages a collection of Uniform objects and maps them to a single Uniform Buffer Object (UBO) on the GPU. Extends EventDispatcher.
Compatibility: WebGLRenderer with ShaderMaterial only.Signature / Usage
const uniformsGroup = new THREE.UniformsGroup();
uniformsGroup.setName('PerFrame');
uniformsGroup.add(new THREE.Uniform(camera.projectionMatrix)); // projection
uniformsGroup.add(new THREE.Uniform(camera.matrixWorldInverse)); // view
// Attach to material
material.uniformsGroups = [uniformsGroup];
// Update per frame
uniformsGroup.uniforms[1].value.copy(camera.matrixWorldInverse);Constructor
new UniformsGroup()Options / Props
| Name | Type | Description |
|---|---|---|
buffer | Float32Array | Packed uniform values |
byteLength | number | Byte length with STD140 alignment |
id | number (readonly) | Unique ID |
isUniformsGroup | boolean (readonly) | Type flag |
name | string | Name of the UBO |
uniforms | Uniform[] | Ordered array of uniforms (must match shader layout) |
usage | Usage constant | Buffer usage hint. Default: StaticDrawUsage |
Methods
add(uniform) // Add a Uniform
addUniform(uniform) // Alias for add()
remove(uniform) // Remove a Uniform
removeUniform(uniform) // Alias for remove()
setName(name) // Set UBO name
setUsage(value) // Set usage hint
dispose() // Free GPU resources
clone() // Clone this group
copy(source) // Copy from another groupNotes
- The order of
uniformsin the array must exactly match the UBO binding layout in the shader. - Call
dispose()to free GPU resources when the group is no longer needed.
Related
- Uniform
BoxGeometry
A geometry for a rectangular cuboid (box/cube) shape. All faces are quads by default.
Signature / Usage
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
width | number | 1 | Length of edges along the X axis |
height | number | 1 | Length of edges along the Y axis |
depth | number | 1 | Length of edges along the Z axis |
widthSegments | number | 1 | Number of segmented rectangular faces along the width |
heightSegments | number | 1 | Number of segmented rectangular faces along the height |
depthSegments | number | 1 | Number of segmented rectangular faces along the depth |
Notes
.parametersholds the constructor arguments used to build the geometry; modifying it after instantiation does not update the geometry.- Use
BoxGeometry.fromJSON( data )to deserialize from a JSON object. - Inherits from
BufferGeometry(EventDispatcher → BufferGeometry → BoxGeometry).
Related
- CylinderGeometry
- PlaneGeometry
CapsuleGeometry
A capsule geometry — a cylinder with hemispherical caps at each end.
Signature / Usage
const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const capsule = new THREE.Mesh( geometry, material );
scene.add( capsule );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
radius | number | 1 | Radius of the capsule |
height | number | 1 | Height of the cylindrical middle section |
capSegments | number | 4 | Number of curve segments used to build each hemispherical cap |
radialSegments | number | 8 | Number of segmented faces around the circumference (minimum 3) |
heightSegments | number | 1 | Number of rows of faces along the height of the middle section (minimum 1) |
Notes
.parametersholds the constructor arguments; modifying it after instantiation does not update the geometry.- Use
CapsuleGeometry.fromJSON( data )to deserialize. - Inherits from
BufferGeometry.
Related
- CylinderGeometry
- SphereGeometry
CircleGeometry
A flat 2D circle (disk) built from triangular segments radiating from a central point. Can also represent a partial sector.
Signature / Usage
const geometry = new THREE.CircleGeometry( 5, 32 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const circle = new THREE.Mesh( geometry, material );
scene.add( circle );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
radius | number | 1 | Radius of the circle |
segments | number | 32 | Number of triangular segments (minimum 3) |
thetaStart | number | 0 | Start angle for the first segment, in radians |
thetaLength | number | Math.PI * 2 | Central angle of the sector in radians; default produces a full circle |
Notes
- The geometry lies in the XY plane, facing the +Z direction.
- A low
segmentscount (e.g. 3, 4, 5, 6) produces regular polygons. .parametersholds the constructor arguments; modifying it after instantiation does not update the geometry.- Use
CircleGeometry.fromJSON( data )to deserialize.
Related
- RingGeometry
- ShapeGeometry
ConeGeometry
A geometry for a cone shape. Extends CylinderGeometry with radiusTop fixed to 0.
Signature / Usage
const geometry = new THREE.ConeGeometry( 5, 20, 32 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const cone = new THREE.Mesh( geometry, material );
scene.add( cone );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
radius | number | 1 | Radius of the cone base |
height | number | 1 | Height of the cone |
radialSegments | number | 32 | Number of segmented faces around the circumference |
heightSegments | number | 1 | Number of rows of faces along the height |
openEnded | boolean | false | Whether the base of the cone is open (true) or capped (false) |
thetaStart | number | 0 | Start angle for the first segment, in radians |
thetaLength | number | Math.PI * 2 | Central angle of the circular sector, in radians |
Notes
- Inherits from
CylinderGeometry(EventDispatcher → BufferGeometry → CylinderGeometry → ConeGeometry). .parametersholds the constructor arguments; modifying it after instantiation does not update the geometry.- Use
ConeGeometry.fromJSON( data )to deserialize.
Related
- CylinderGeometry
CylinderGeometry
A geometry for a cylinder (or truncated cone) with configurable top/bottom radii, height, and segmentation.
Signature / Usage
const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const cylinder = new THREE.Mesh( geometry, material );
scene.add( cylinder );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
radiusTop | number | 1 | Radius of the cylinder at the top |
radiusBottom | number | 1 | Radius of the cylinder at the bottom |
height | number | 1 | Height of the cylinder |
radialSegments | number | 32 | Number of segmented faces around the circumference |
heightSegments | number | 1 | Number of rows of faces along the height |
openEnded | boolean | false | Whether the ends are open (true) or capped (false) |
thetaStart | number | 0 | Start angle for the first segment, in radians |
thetaLength | number | Math.PI * 2 | Central angle of the circular sector, in radians |
Notes
- Setting
radiusTopto0produces a cone shape (see alsoConeGeometry). .parametersholds the constructor arguments; modifying it after instantiation does not update the geometry.- Use
CylinderGeometry.fromJSON( data )to deserialize. - Inherits from
BufferGeometry.
Related
- ConeGeometry
- CapsuleGeometry
DodecahedronGeometry
A geometry for a dodecahedron — a polyhedron with 12 pentagonal faces. Setting detail > 0 subdivides the faces to approximate a sphere.
Signature / Usage
const geometry = new THREE.DodecahedronGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const dodecahedron = new THREE.Mesh( geometry, material );
scene.add( dodecahedron );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
radius | number | 1 | Radius of the dodecahedron |
detail | number | 0 | Subdivision level; values > 0 add vertices and round the shape |
Notes
- Inherits from
PolyhedronGeometry(EventDispatcher → BufferGeometry → PolyhedronGeometry → DodecahedronGeometry). .parametersholds the constructor arguments; modifying it after instantiation does not update the geometry.- Use
DodecahedronGeometry.fromJSON( data )to deserialize.
Related
- PolyhedronGeometry
- IcosahedronGeometry
- OctahedronGeometry
- TetrahedronGeometry
EdgesGeometry
A helper geometry that extracts and renders the edges of another geometry based on a face-normal angle threshold. Used with LineSegments to display edge outlines.
Signature / Usage
const geometry = new THREE.BoxGeometry();
const edges = new THREE.EdgesGeometry( geometry );
const line = new THREE.LineSegments( edges );
scene.add( line );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
geometry | BufferGeometry | null | The source geometry from which edges are extracted |
thresholdAngle | number | 1 | Minimum angle (degrees) between adjacent face normals for an edge to be rendered |
Notes
- An edge is included only when the angle between the normals of the two adjoining faces exceeds
thresholdAngle. - Serialization/deserialization of
EdgesGeometryis not currently supported. - Inherits from
BufferGeometry.
Related
- WireframeGeometry
ExtrudeGeometry
Creates a 3D geometry by extruding a 2D Shape along a path or straight depth. Supports beveling and custom UV generation.
Signature / Usage
const shape = new THREE.Shape();
shape.moveTo( 0, 0 );
shape.lineTo( 0, 8 );
shape.lineTo( 12, 8 );
shape.lineTo( 12, 0 );
shape.lineTo( 0, 0 );
const geometry = new THREE.ExtrudeGeometry( shape, { depth: 4, bevelEnabled: false } );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
shapes | Shape \ | Shape[] | — |
curveSegments | number | 12 | Number of points on curves |
steps | number | 1 | Subdivisions along the extrusion depth |
depth | number | 1 | Depth to extrude the shape |
bevelEnabled | boolean | true | Apply beveling to the shape |
bevelThickness | number | 0.2 | Depth the bevel goes into the original shape |
bevelSize | number | bevelThickness - 0.1 | Distance from the shape outline the bevel extends |
bevelOffset | number | 0 | Distance from the shape outline where the bevel starts |
bevelSegments | number | 3 | Number of bevel layers |
extrudePath | Curve | null | 3D spline path to extrude along (bevels not supported with this option) |
UVGenerator | Object | — | Custom UV generator object |
Notes
.parametersholds the constructor arguments; modifying it after instantiation does not update the geometry.- When
extrudePathis set, beveling is ignored. - Inherits from
BufferGeometry.
Related
- ShapeGeometry
IcosahedronGeometry
A geometry for an icosahedron — a polyhedron with 20 equilateral triangular faces. Setting detail > 0 subdivides faces to approximate a sphere.
Signature / Usage
const geometry = new THREE.IcosahedronGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const icosahedron = new THREE.Mesh( geometry, material );
scene.add( icosahedron );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
radius | number | 1 | Radius of the icosahedron |
detail | number | 0 | Subdivision level; values > 0 add vertices and round the shape |
Notes
- Inherits from
PolyhedronGeometry(EventDispatcher → BufferGeometry → PolyhedronGeometry → IcosahedronGeometry). .parametersholds the constructor arguments; modifying it after instantiation does not update the geometry.- Use
IcosahedronGeometry.fromJSON( data )to deserialize.
Related
- PolyhedronGeometry
- DodecahedronGeometry
- OctahedronGeometry
- TetrahedronGeometry
LatheGeometry
Creates a geometry with axial symmetry by rotating a set of 2D points around the Y axis. Useful for vase, bowl, or spindle shapes.
Signature / Usage
const points = [];
for ( let i = 0; i < 10; i++ ) {
points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
}
const geometry = new THREE.LatheGeometry( points );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const lathe = new THREE.Mesh( geometry, material );
scene.add( lathe );Options / Props
| Name | Type | Default | Description |
|---|---|---|---|
points | Array\<Vector2 \ | Vector3\> | — |
segments | number | 12 | Number of circumference segments |
phiStart | number | 0 | Starting angle in radians |
phiLength | number | Math.PI * 2 | Radian range of the lathed section; 2 * PI = closed surface |
Notes
- The profile is revolved around the Y axis.
- Each point's X coordinate must be greater than zero; a value of 0 collapses to the axis and may produce degenerate geometry.
.parametersholds the constructor arguments; modifying it after instantiation does not update the geometry.- Use
LatheGeometry.fromJSON( data )to deserialize.
Related
- TubeGeometry
- ExtrudeGeometry