Three.js - A Visual Guide

Every concept in Three.js explained visually. 96 illustrated breakdowns covering geometry, materials, cameras, shaders, post-processing, physics, audio and more. No prior 3D experience required - just scroll.

96 Visual Breakdowns r183 WebGL + WebGPU TSL / Node Shaders Physics · Audio · Loaders
▶ Watch Full Video 📄 Official Docs ⬡ GitHub

Full Encyclopedia Video

All 96 slides in sequence - 7 minutes covering every Three.js concept from geometry to shaders.

01

Overview & Architecture

Three.js is a JavaScript library that wraps WebGL (and now WebGPU) into an approachable scene graph API. The core idea: you describe what you want to show - objects, lights, a camera - and the renderer figures out how to draw it on the GPU. The architecture is simple: a Scene holds Object3Ds, a Camera defines the view, and a Renderer draws it all every frame.

Three.js Architecture Overview

Three.js - Full Architecture Map

Every Three.js scene follows the same pattern: create a Scene, add Mesh objects (Geometry + Material), position a Camera, and hand it all to the Renderer which sends draw calls to the GPU. The render loop runs at 60fps via requestAnimationFrame.

Understanding this flow is the foundation for everything else in this guide. Every other concept - shaders, post-processing, physics - sits on top of this core loop.

// The minimal Three.js scene const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 75, width/height, 0.1, 1000 ); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setAnimationLoop( () => renderer.render( scene, camera ) );
02

Geometry

Geometry defines the shape of a 3D object - the vertices, edges and faces that make up its surface. Under the hood, everything is a BufferGeometry: flat typed arrays of vertex data (position, normal, UV, color, index) sent directly to the GPU. Three.js ships 21 built-in geometry constructors, plus the tools to create your own from scratch or load from files.

Three.js Geometry Types

All 21 Built-in Geometry Types

Three.js provides a geometry for almost every common shape out of the box. The primitives - Box, Sphere, Cylinder, Cone, Torus - cover most game and visualisation needs. The parametric types - LatheGeometry, TubeGeometry, ExtrudeGeometry - let you create complex shapes from curves and profiles. The polyhedra - Icosahedron, Dodecahedron, Octahedron - produce mathematically perfect symmetric shapes.

All geometries have a widthSegments/heightSegments parameter that controls polygon density. More segments = smoother shape but higher vertex count. TorusKnotGeometry creates intricate knotted shapes via p and q winding parameters.

// Create geometry with detail level const geo = new THREE.SphereGeometry( radius, widthSegs, heightSegs ); const knot = new THREE.TorusKnotGeometry( 10, 3, 100, 16, p, q );
03

Materials

Materials control how geometry looks when rendered - its colour, shininess, transparency, and how it reacts to light. Three.js has materials for every use case and performance budget: from the cheapest flat MeshBasicMaterial (no lighting) to the fully physics-based MeshPhysicalMaterial with clearcoat, sheen, iridescence, transmission and subsurface scattering. The right material makes the difference between flat and photorealistic.

Three.js Materials

All Material Types - From Basic to Physically Based

MeshBasicMaterial - No lighting calculation. Always shows flat colour or texture. Zero GPU cost. Use for UI, wireframes, non-lit stylised objects.

MeshLambertMaterial - Diffuse-only lighting (no specular). Calculated per-vertex, not per-pixel. Fast and decent for matte surfaces. Not realistic but works great for stylised scenes.

MeshPhongMaterial - Adds a specular highlight (Blinn-Phong model). shininess controls the tightness of the specular spot. Classic 3D look, faster than PBR.

MeshStandardMaterial - Physically-based rendering (PBR). Metalness/roughness workflow. roughness=0 is mirror-like, roughness=1 is fully diffuse. Correctly responds to environment maps and IBL lighting.

MeshPhysicalMaterial - Extends Standard with clearcoat, sheen (velvet), iridescence, transmission (glass), thickness (refraction depth) and anisotropy. The most realistic material.

MeshToonMaterial - Cel-shaded cartoon look using a gradient map to define the step in shading bands. Combine with an outline pass for a complete anime aesthetic.

// Standard PBR material const mat = new THREE.MeshStandardMaterial({ color: 0xff6600, roughness: 0.3, metalness: 0.8, normalMap: normalTex, envMapIntensity: 1.5 }); // Physical material (glass) const glass = new THREE.MeshPhysicalMaterial({ transmission: 1, thickness: 0.5, roughness: 0, ior: 1.5 });
04

Lighting

Lighting is what makes a 3D scene feel real. A well-lit scene communicates depth, weight, material type and mood. Three.js offers 7 light types - from the ambient fill that eliminates harsh shadows to the precise spotlight casting dramatic shadows. Only DirectionalLight, SpotLight and PointLight can cast shadows; each uses a shadow map technique (rendering the scene from the light's POV to determine occlusion).

Three.js Lighting

7 Light Types + Shadow Maps

AmbientLight - Adds a flat uniform colour to every surface. No direction, no shadows, no highlights. Use it as a base fill to prevent completely black shadows. Too much makes scenes look flat.

DirectionalLight - Infinite parallel rays, like the sun. All shadows are parallel (use OrthographicCamera for shadow map). Position sets the direction; target sets what it points at. The workhorse outdoor light.

PointLight - Radiates in all directions from a point, like a light bulb. Has distance and decay for falloff. Casts shadows in 6 directions (expensive - uses CubeCamera internally).

SpotLight - Cone-shaped beam, like a flashlight or stage light. angle sets cone width, penumbra softens the edge. Position + target defines the beam direction. Great for dramatic lighting.

HemisphereLight - Sky colour from above, ground colour from below. Two-colour gradient fill that simulates outdoor ambient light. No shadows. Very cheap and effective for outdoor scenes.

RectAreaLight - Soft rectangular light source (like a fluorescent tube or window). Works only with MeshStandardMaterial and MeshPhysicalMaterial. Requires RectAreaLightUniformsLib. No shadow support.

LightProbe - Encodes ambient lighting as spherical harmonics (SH). Low-frequency ambient lighting baked from the environment - smooth, cheap, and great for matching captured real-world lighting.

// Three-point lighting setup const key = new THREE.DirectionalLight( 0xffffff, 2 ); key.castShadow = true; key.shadow.mapSize.set( 2048, 2048 ); const fill = new THREE.HemisphereLight( 0x8888ff, 0x443322, 0.5 ); const rim = new THREE.PointLight( 0x00ffff, 1, 50 );
05

Scene Objects

Everything in a Three.js scene is an Object3D - the base class providing position, rotation, scale, visibility, and parent/child hierarchy. From the basic Mesh to the GPU-instanced InstancedMesh that draws 100,000 copies in a single draw call, each object type exists to solve a specific rendering challenge.

Three.js Scene Objects

All Object Types in the Scene Graph

Mesh - The fundamental 3D object: geometry + material. Supports position, rotation, scale, visibility, shadow casting/receiving. Most of your scene will be Meshes.

InstancedMesh - Renders N copies of the same geometry+material in a single GPU draw call. Set each instance's transform via setMatrixAt(i, matrix). Renders a forest of 100,000 trees as fast as one tree. Essential for performance.

BatchedMesh (r159+) - Like InstancedMesh but allows different geometries in the same draw call. Add and remove geometry slots dynamically without recreating the whole buffer.

SkinnedMesh - A Mesh deformed by a Skeleton (bone hierarchy). Bones are Object3Ds - moving them deforms the mesh via skinning weights stored in the geometry. Used for all character animation.

Points - Renders each vertex as a screen-aligned point/sprite. Used for particle systems - fire, smoke, stars, galaxy simulations. PointsMaterial controls size, texture, colour and size attenuation with distance.

Line / LineSegments / LineLoop - Draws line primitives. LineSegments draws disconnected pairs. LineLoop closes the path. Used for debug geometry, wireframes, connector lines, graphs.

Sprite - A billboard that always faces the camera. Sized in screen space. Used for labels, icons, particle effects and 2D elements in 3D space.

Group - An empty Object3D used as a parent container. Transforming a Group moves all children together. Fundamental for scene organisation and hierarchical animation.

LOD - Automatically swaps between high/medium/low poly versions based on camera distance. Add levels with lod.addLevel(mesh, distance). Essential for large open-world scenes.

07

Cameras

The camera defines how the 3D scene is projected onto your 2D screen. PerspectiveCamera mimics human vision - objects farther away appear smaller. OrthographicCamera has no perspective - objects stay the same size regardless of distance, giving the classic isometric game look. The remaining cameras serve specialised purposes: real-time reflections, multi-viewport, and VR.

PerspectiveCamera FOV

PerspectiveCamera - Field of View

The most common camera in Three.js. Takes four parameters: fov (vertical field of view in degrees), aspect (width/height of the canvas), near (closest visible distance), far (furthest visible distance).

FOV 30° - Telephoto/sniper zoom. Looks flat, compressed perspective. Objects appear very close together. Used in sniper rifle scopes, architectural renders where you want distortion-free perspective.

FOV 75° - Standard FPS game feel. Natural perspective, good depth. Most third-person games and 3D web apps use 60–75°.

FOV 120° - Ultra-wide angle, strong fisheye effect. See a huge amount of the scene but with significant edge distortion. Used for racing cockpits, arena shooters, action games.

const camera = new THREE.PerspectiveCamera( fov, // field of view in degrees (vertical) aspect, // canvas width / canvas height near, // near clipping plane (e.g. 0.1) far // far clipping plane (e.g. 1000) );
OrthographicCamera

OrthographicCamera - Parallel Projection

No perspective. Objects at the same size remain the same size regardless of distance from camera. This is the camera for isometric strategy games, top-down 2D games, CAD/engineering views, and shadow maps for directional lights. Takes left, right, top, bottom, near, far - defining a box-shaped frustum.

CubeCamera

CubeCamera - 360° Environment Capture

Renders the scene 6 times (±X, ±Y, ±Z faces) into a WebGLCubeRenderTarget, producing a cubemap texture of the environment. Place it inside/near an object to capture its reflection environment. Update it each frame for dynamic real-time reflections - or capture once and cache for static reflections.

const cubeRT = new THREE.WebGLCubeRenderTarget( 256 ); const cubeCamera = new THREE.CubeCamera( 0.1, 100, cubeRT ); sphere.material.envMap = cubeRT.texture; // use as reflection
ArrayCamera

ArrayCamera - Multiple Viewports

An array of sub-cameras each defining a viewport region (x, y, width, height in normalised 0–1 coordinates). Used for split-screen multiplayer games, security camera monitor UIs, or rendering the same scene from multiple simultaneous viewpoints. More efficient than rendering multiple separate scenes.

StereoCamera

StereoCamera - VR & 3D Anaglyph

Two cameras separated by an eye offset (eyeSep parameter, default 0.064 metres). Renders left and right eye views side by side. Used with VR headsets (also see XRManager for full WebXR support) or red-cyan anaglyph 3D for classic stereoscopic effect.

08

Textures

Textures are images mapped onto geometry surfaces to add visual detail without adding geometry. A UV map on each vertex tells the GPU which part of the texture to sample there. Three.js supports flat colour textures, normal maps for fake surface depth, full PBR texture sets, video textures, HDR environments, and compressed GPU-native formats for 4–8× less VRAM usage.

Texture Basics

Texture Basics & UV Mapping

Every vertex has a UV coordinate (0–1 range) that maps it to a position in a 2D texture. UV 0,0 is bottom-left, 1,1 is top-right. Use texture.repeat to tile, texture.offset to shift, texture.wrapS/T to control how it repeats at edges (ClampToEdge, Repeat, MirroredRepeat).

const tex = new THREE.TextureLoader().load( 'wood.jpg' ); tex.repeat.set( 4, 4 ); tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
Normal Maps

Normal Maps - Fake Surface Detail

An RGB image where each pixel encodes a surface normal direction. The lighting model uses these fake normals to simulate bumps, scratches, fabric weave and detail - without adding a single polygon. The result looks 3D under moving light but the geometry remains flat. Essential for game-quality assets.

PBR Texture Set

PBR Texture Set

A full physically-based rendering texture set for MeshStandardMaterial: Albedo (base colour, no lighting), Normal (surface detail direction), Roughness (how blurry reflections are - 0=mirror, 1=fully matte), Metalness (is it metal? - 0=non-metal, 1=metal), AO (ambient occlusion - contact shadows). Optional: Emissive, Displacement, Opacity.

Skybox

CubeTexture - Skybox & Environment

6 images (±X, ±Y, ±Z) assembled into a cubemap. Set scene.background = cubeTexture for a skybox. Set scene.environment = cubeTexture to use it as IBL (image-based lighting) - it will automatically light all PBR materials, providing realistic reflections and ambient lighting from the environment.

Video Texture

VideoTexture - Live Video on Surfaces

Maps a playing HTML <video> element onto a 3D surface in real time. The texture updates every frame to match the video playback. Used for in-game TVs, screens, portals, projectors and video walls. Must call videoTexture.needsUpdate = true each frame.

Data Texture

DataTexture - Programmatic Textures

Create textures directly from typed arrays in JavaScript - no image file needed. Pass a Uint8Array or Float32Array of pixel values. Used for heatmaps, heightmaps, scientific data visualisation, and GPU-computed textures from compute shaders.

HDR Environment

HDR / EXR Environment Maps

High dynamic range images store light values far above 1.0, capturing the full range from deep shadow to bright sun. Load .hdr (RGBE format) with RGBELoader or .exr with EXRLoader, then pass to PMREMGenerator to prefilter for PBR rendering. The result: metal surfaces reflect actual sunlight, not just a flat colour.

Compressed Textures

Compressed Textures - KTX2 / Basis

GPU-native compressed formats stay compressed in VRAM - 4–8× less memory than PNG. KTX2 with Basis supercompression is the modern standard: a single .ktx2 file transcodes to the best format per device (DXT/BC for desktop, ETC for Android, ASTC for iOS). Use KTX2Loader + MSDF worker. Critical for mobile performance.

09

Renderer Features

The renderer transforms your scene into pixels. Three.js has WebGLRenderer (the proven standard, works everywhere) and WebGPURenderer (the modern future, compute shaders, better performance). Both share a common abstraction layer so most code runs on either. Key features: shadow maps, environment mapping, tone mapping, anti-aliasing, and render targets for off-screen rendering.

Shadow Types

Shadow Map Types

BasicShadowMap - Fastest, hard edges. PCFShadowMap - Percentage-closer filtering, smoother edges. PCFSoftShadowMap - Softer PCF with kernel blur. VSMShadowMap - Variance shadow maps, very soft, no peter-panning artifact, but has light bleeding on transparent objects. Set via renderer.shadowMap.type = THREE.PCFSoftShadowMap.

Environment Mapping

Environment Mapping & IBL

Set scene.environment = pmremTexture to enable image-based lighting for all PBR materials simultaneously. Metal objects reflect the environment, rough objects receive diffuse IBL. envMapIntensity scales the strength. Combine with a visible skybox for complete immersive environments.

Tone Mapping

Tone Mapping

HDR rendering produces light values above 1.0. Tone mapping squashes the full HDR range into the 0–1 display range. NoToneMapping clips. ReinhardToneMapping is photographic. ACESFilmicToneMapping gives a cinematic S-curve look (most popular). AgXToneMapping (r158+) is physically accurate with correct hue preservation.

Anti-Aliasing

Anti-Aliasing

Built-in MSAA: pass antialias: true to WebGLRenderer. Post-process options: FXAA (fast, slight blur), SMAA (better quality, two-pass). TAA (temporal AA) provides highest quality by accumulating sub-pixel samples over multiple frames - only works on static or slow-moving scenes.

Render Targets

Render Targets - Off-screen Rendering

WebGLRenderTarget redirects render output to a texture instead of the screen. That texture can then be applied to a 3D surface (a TV showing another camera), used as input to post-processing, or read back to CPU. The basis for all multi-pass rendering techniques.

WebGL vs WebGPU

WebGL vs WebGPU

WebGL: Based on OpenGL ES 2.0/3.0. ~98% browser support. Proven, stable. Limited to graphics pipeline. WebGPU: Modern explicit GPU API. Compute shaders, better multi-threading, lower driver overhead. ~70% browser support (2024). Three.js wraps both behind the same API - switch with import WebGPURenderer from 'three/webgpu'.

Compute Shaders

Compute Shaders (WebGPU only)

GPU programs running outside the graphics pipeline. Simulate millions of particles, fluid dynamics, cloth, or crowds entirely on the GPU - reading and writing storage buffers. Available via WebGPURenderer with TSL's compute() function. Orders of magnitude faster than CPU for parallelisable problems.

Render Pipeline

Render Pipeline - Frame by Frame

Scene graph → frustum culling → sort render list by material (opaque first, transparent last, by z-depth) → set render state → GPU: vertex shader (transforms positions to clip space) → rasterisation (converts triangles to fragments) → fragment shader (computes pixel colour) → framebuffer → screen. Understanding this helps diagnose performance and visual issues.

10

Post-Processing Effects

Post-processing applies screen-space effects after the scene is rendered to a texture. EffectComposer chains passes together - the output of one feeds into the next. Three.js ships 20+ built-in passes and you can write custom fullscreen shader passes. The difference between a raw render and a cinematic scene is almost entirely post-processing.

EffectComposer

EffectComposer - The Post-Processing Pipeline

RenderPass renders the scene to a texture. Each subsequent pass reads from the previous pass's texture, applies an effect, and writes to the next. OutputPass or RenderPixelatedPass writes to screen. The order matters - bloom after SSAO, before colour grading.

const composer = new EffectComposer( renderer );
composer.addPass( new RenderPass( scene, camera ) );
composer.addPass( new UnrealBloomPass( resolution, strength, radius, threshold ) );
composer.addPass( new OutputPass() );
Bloom

Bloom / UnrealBloomPass

Bright areas bleed glow into surrounding pixels, simulating the way intense light overloads a camera lens or your eyes. Adjust threshold (minimum brightness to bloom), strength (intensity), radius (spread distance). Selective bloom: use two scenes - one with only emissive objects, run bloom on that, composite back.

SSAO

SSAO - Screen-Space Ambient Occlusion

Darkens concave areas - crevices, corners, where surfaces meet - to simulate ambient light being blocked. Adds ground and weight to objects. Computed entirely from the depth buffer in screen space, so it's cheap and doesn't require ray-tracing. SAOPass in Three.js examples.

Depth of Field

Depth of Field (Bokeh)

Objects outside the focal plane blur with characteristic disc-shaped bokeh, mimicking a real camera lens with a narrow depth of field. focus sets focal distance, aperture controls blur amount, maxblur clamps the maximum. Draws the viewer's eye to the focal point.

Film Grain

Film Grain & Noise

Adds time-varying noise to every pixel, simulating photographic film grain or sensor noise. Softens the overly-clean look of CGI and adds cinematic character. FilmPass in Three.js adds grain + optional scanlines. Animated per-frame so it looks organic, not like a static texture overlay.

Glitch Effect

Glitch Effect

Digital corruption: random horizontal band shifts, RGB channel separation, noise blocks. GlitchPass triggers random glitch bursts at goWild intensity, or stays subtle at low settings. Perfect for cyberpunk, horror, hack/error UI moments, and sci-fi transitions.

Outline

Outline - Selection Highlight

OutlinePass renders selected objects with a coloured edge glow. Objects added to selectedObjects array get outlined. Control colour, thickness (edgeThickness) and glow (edgeStrength). Essential for game selection UIs, hover highlighting, and emphasising interactive objects.

Color Grading

Color Grading / LUT

A 3D Look-Up Table (LUT) remaps the output colours of the entire frame - like an Instagram filter but for your 3D scene. LUTPass loads a .cube or .png LUT file. Transform any scene: warm cinematic orange-teal, cold horror blue, vintage sepia, crushed blacks. Industry standard.

Motion Blur

Motion Blur

Blurs fast-moving objects along their trajectory, as a real camera shutter would capture during exposure. Gives movement weight, speed and physicality. Can be per-object (accumulate velocity vectors) or full-screen camera motion blur. Makes action scenes feel kinetic.

God Rays

God Rays - Volumetric Light Shafts

Visible shafts of light when a bright source is partially occluded - sun through clouds, lamp through fog. GodraysPass renders the scene silhouette from the light position, then applies radial blur outward. The result: volumetric-looking light without actual volumetric simulation.

Chromatic Aberration

Chromatic Aberration

Offsets the R, G and B colour channels by slightly different amounts in screen space, creating colour fringing at high-contrast edges. Mimics cheap, damaged or fisheye camera lenses. A staple of lo-fi, retro, horror and vaporwave aesthetics. Subtle amounts add believable lens character.

Pixel Retro

Pixel / Retro Effect

Renders the scene at a low resolution (e.g. 320×240) then upscales with nearest-neighbour filtering. The result looks like an old video game - blocky pixels, visible colour banding. RenderPixelatedPass in Three.js. Combine with a dithering shader and limited colour palette for a full Game Boy or NES aesthetic.

11

Controls

Controls translate user input (mouse, keyboard, touch, gamepad) into camera or object movement. Three.js ships 8+ control types in the addons (jsm/controls/). The right choice depends entirely on the use case - don't use OrbitControls for an FPS game, don't use PointerLockControls for a 3D product viewer.

OrbitControls

OrbitControls - Camera Around Target

The default for 3D model viewers and product configurators. Left-drag orbits, right-drag pans, scroll zooms. Set target to the point the camera orbits around. enableDamping=true adds smooth deceleration. autoRotate for hands-free spinning displays.

FirstPersonControls

FirstPersonControls - WASD + Mouse Look

WASD movement through the scene, mouse movement rotates the view. Camera can move through the scene freely (no collision). Note: PointerLockControls is preferred for games as it locks/hides the cursor. FirstPersonControls is better for architectural walk-throughs where you still want a visible cursor.

FlyControls

FlyControls - 6 Degrees of Freedom

Full 6DOF flight - move forward/back, strafe left/right, ascend/descend, yaw, pitch, roll. No ground plane constraint. Ideal for space games, drone simulators, and exploring large 3D environments from any angle. Use movementSpeed and rollSpeed to tune feel.

MapControls

MapControls - Top-Down Map

Variant of OrbitControls optimised for top-down map navigation. Right-drag rotates, left-drag pans the ground plane, scroll zooms. The camera always points roughly downward. Perfect for strategy games, GIS applications, city planners and data visualisation maps.

TransformControls

TransformControls - 3D Object Gizmo

Attach to any Object3D to show a manipulator gizmo - arrows for translation, rings for rotation, handles for scale. Press T/R/S to switch modes. Drag axes to constrain to a single axis. Essential for any in-browser 3D editor or level editor. Fire objectChange event to react to modifications.

PointerLockControls

PointerLockControls - FPS Camera

Locks and hides the mouse cursor (browser Pointer Lock API). All mouse delta movement directly rotates the camera - no cursor visible, no screen edge limits. Call controls.lock() on a user click gesture. Standard for first-person games. Combine with WASD keyboard handler for full FPS controls.

12

Node System / TSL - Three Shading Language

TSL is Three.js's shader authoring system written entirely in JavaScript. Instead of writing GLSL strings, you compose shader graphs from function nodes - color(), texture(), add(), normalMap(), noise() - and TSL compiles them to GLSL for WebGL or WGSL for WebGPU automatically. No raw shader strings, no manual uniform management, no platform-specific code.

TSL Concept

What is TSL?

Write shaders in JavaScript, run on GPU. Assign any node expression to material properties: material.colorNode, material.emissiveNode, material.positionNode. The node graph compiles to the correct shader language at runtime.

import { color, texture, mix, uv, time } from 'three/tsl';
const mat = new MeshStandardNodeMaterial();
mat.colorNode = mix( color(0xff0000), color(0x0000ff), sin( time ) );
Noise Functions

Noise Functions

TSL includes several GPU noise functions: mx_noise_float() for Perlin-style smooth noise, mx_worley_noise() for cellular/Voronoi patterns, checker(), mx_fractal_noise() for fBm (fractal Brownian motion). All run on GPU - perfect for animated terrain, clouds, fire, water, procedural textures.

TSL Math Operations

Math Operations in TSL

All standard shader math functions available as TSL nodes: add(), sub(), mul(), div(), mix(), clamp(), smoothstep(), pow(), abs(), sin(), cos(), floor(), fract(), length(), dot(), cross(), normalize(). Chain them to build any mathematical shader effect.

Fresnel

Fresnel / Rim Lighting

The Fresnel effect: surfaces become more reflective at glancing angles (edge of a sphere vs centre). Water, glass, car paint, skin all exhibit this. In TSL: fresnel() outputs 0 at the centre (facing camera) and 1 at the edge. Mix it into emissive or colour for rim glow effects.

Displacement

Vertex Displacement

Assign a TSL expression to material.positionNode to move vertices in the vertex shader. Animate terrain from a heightmap, make ocean waves from sine functions, breathe life into characters, create plasma sphere effects - all on GPU with zero CPU overhead.

Triplanar

Triplanar Mapping

Projects a texture from X, Y and Z axes simultaneously and blends them based on the surface normal. The result: any shape gets correctly textured without UV unwrapping. triplanarTexture() in TSL. Essential for terrain, caves, organic shapes and anything where UV mapping is impractical.

PBR Node Breakdown

PBR Node Breakdown

How TSL texture nodes wire into a full PBR material: texture(albedoMap)colorNode, normalMap(normalTex)normalNode, texture(roughTex).rroughnessNode, texture(metalTex).bmetalnessNode. Each property accepts any node expression.

GPGPU

GPGPU - GPU Particle Simulation

Use compute() nodes (WebGPU only) to simulate millions of particles entirely on the GPU. Each particle's position and velocity is stored in a storage buffer. The compute shader updates all particles in parallel. Results feed directly into InstancedMesh matrices - no CPU data transfer each frame.

Procedural Shaders

Procedural Shaders

Generate every pixel purely from mathematics - no textures, no files, no loading time. Checkerboard, gradient, polar coordinates, mandelbrot, voronoi, plasma, sine wave patterns. All computed per-pixel at 60fps on GPU. Combine noise + trig functions for infinite detail at any scale.

Custom Shader

Custom Shader - Full Creative Control

Assign any TSL expression to any material property. Combine noise, math, time, UV coordinates and texture samples in any way you imagine. Or use raw ShaderMaterial/RawShaderMaterial with hand-written GLSL for absolute control. This is where Three.js becomes a creative coding environment.

13

Animation

Three.js includes a complete keyframe animation system. AnimationClip stores named tracks of keyframed values. AnimationMixer plays clips on an object, handling speed, looping, blending and crossfading between multiple clips. Used for everything from a spinning cube to fully rigged character animation.

Keyframes

Keyframes & Tracks

A KeyframeTrack stores the property name (.position[x]), an array of times (seconds), and an array of values. Multiple tracks form an AnimationClip. The interpolant (linear, smooth cubic, or discrete step) fills values between keyframes. Any Object3D property can be animated: position, rotation, scale, material colour, morph weight.

Walk Cycle

Walk Cycle

~8 key poses timed so the last frame flows back into the first. The mixer loops the clip and the character walks indefinitely. Walk cycles are the foundation of character animation - everything else (run, jump, combat) layers on top or crossfades from it.

Blend / Crossfade

Blend & Crossfade

AnimationMixer blends multiple simultaneous actions by their weight property. action.crossFadeTo(otherAction, duration) smoothly transitions weight from one clip to another over the duration - walk smoothly becomes run, idle flows into attack, land fades from falling.

Morph Targets

Morph Targets - Blend Shapes

Pre-baked vertex positions stored in geometry. mesh.morphTargetInfluences[i] = 0..1 blends between base geometry and a target shape. Blend multiple targets simultaneously. Used for facial expressions, lip-sync, secondary deformations, and smooth shape transformations. Common in glTF character files.

Skeletal Animation

Skeletal Animation - Bone Rigs

A Skeleton is a hierarchy of Bone objects (Object3Ds). Each vertex in the SkinnedMesh is influenced by 1–4 bones with blend weights (stored as skinIndex and skinWeight attributes). Move/rotate bones and the mesh follows. The complete character animation pipeline used in games.

Additive Animation

Additive Animation

An additive layer adds its delta values on top of a base pose instead of replacing it. Set action.blendMode = THREE.AdditiveAnimationBlendMode. Breathing, head-look, flinch reactions and facial emotions can all be independent additive layers playing simultaneously on top of locomotion.

Animation Curves

Animation Curves - Interpolation

How values change between keyframes: InterpolateLinear (straight line, robotic), InterpolateSmooth (cubic Catmull-Rom, natural), InterpolateDiscrete (instant step, snappy). Ease-in/ease-out curves make animations feel physical - things accelerate and decelerate rather than moving at constant speed.

AnimationMixer

AnimationMixer Concept

One mixer per animated object. mixer.clipAction(clip) returns an AnimationAction. Set action.play(), action.weight (blend amount), action.timeScale (speed). Call mixer.update(delta) every frame in the render loop. Multiple actions blend automatically by their weights.

14

Audio

Three.js integrates the Web Audio API into the scene graph. AudioListener attaches to the camera and acts as the player's ears. PositionalAudio attaches to 3D objects and automatically adjusts volume and stereo panning based on distance and angle from the listener - walk towards an explosion and it gets louder, walk past it and it pans side to side.

Spatial Audio

Spatial Audio - 3D Positioning

AudioListener on the camera = the player's ears. PositionalAudio on a 3D object = a sound source in the world. The Web Audio PannerNode automatically computes volume, left/right panning, and doppler shift from the relative positions and velocities. Walk through a scene and sounds change as expected.

Audio Falloff

Audio Falloff - Distance Curves

rolloffFactor controls how fast volume drops. distanceModel: linear (even drop to maxDistance), inverse (halves every doubling of distance - physically correct), exponential (extreme drop off). refDistance is where attenuation begins; maxDistance is where volume hits 0.

AudioAnalyser

AudioAnalyser - Frequency Visualisation

Wraps Web Audio's AnalyserNode. Call analyser.getFrequencyData() each frame - returns a Uint8Array of FFT frequency bins from bass to treble. Use those 128/256 values to drive anything: geometry heights, emissive intensity, particle velocities, colour shifts. Music-reactive visuals.

Audio Cones

Audio Cones - Directional Sound

PositionalAudio supports directionality via inner/outer cone angles. coneInnerAngle: full volume zone. coneOuterAngle: transition zone. coneOuterGain: volume at and beyond outer cone. Perfect for NPCs, speakers pointing in a direction, vehicle exhausts, vents.

15

Special Objects & Effects

Three.js addons include high-level pre-built objects for visual needs that would take weeks to build from scratch - animated ocean water, procedural sky, real-time mirror reflections, lens flares, HTML elements in 3D space, and GPU-instanced forests. All in jsm/objects/ and ready to drop into any scene.

Water

Water - Ocean Surface

Animated water surface using two normal map textures scrolling at different speeds and angles for complex wave patterns. Reflects the sky, refracts the scene below, and responds to sunDirection for specular sun glints. Water2 adds more complex dual-normal wave patterns for rivers, pools and oceans.

Sky

Sky - Procedural Preetham Model

A physically-based sky shader (Preetham 1999 atmospheric scattering model). Parameters: turbidity (haze), rayleigh (blue sky scattering), mieCoefficient/mieDirectionalG (sun halo size), sunPosition. No textures needed - full dawn-to-dusk cycle in real-time from equations alone.

Reflector

Reflector - Real-Time Mirror

Renders the scene from a reflected camera perspective into a texture, then applies that texture to the reflective plane - a real-time mirror. Used for glossy floors, mirrors, calm water. ReflectorForSSRPass adds screen-space reflections for any surface (not just flat planes).

Lensflare

Lensflare

Adds hexagonal aperture flare artefacts along the axis from a bright light to screen centre - mimicking a camera lens. Attach Lensflare to any light/object and add textured flare elements at different screen distances. Occlusion-tested: disappears when the light source is hidden.

CSS3D

CSS3DObject - HTML Elements in 3D

CSS3DRenderer overlays a DOM layer perfectly aligned with the WebGL scene. CSS3DObject wraps any HTML element (including live iframes, video, interactive UI) and positions it in 3D space. The CSS transform matches Three.js camera perspective exactly. Combine with WebGL renderer for mixed HTML/3D experiences.

Instancing

Instancing - One Draw Call, 100,000 Objects

InstancedMesh renders N copies of the same geometry+material in a single GPU draw call. Each instance has its own 4×4 transform matrix (position, rotation, scale) and optional per-instance colour. Rendering a forest of 100,000 trees takes the same CPU time as rendering one tree.

LOD

LOD - Level of Detail

LOD.addLevel(mesh, distance) - the closest level shows full detail; as camera distance increases, lower-poly versions swap in automatically. Halving polygon count at double distance maintains visual quality while dramatically reducing GPU load. Essential for open worlds and large scenes.

Particles

Sprite Particles - Points System

Points geometry + PointsMaterial renders each vertex as a screen-aligned billboard. size controls point size, sizeAttenuation enables perspective scaling, map applies a texture, vertexColors allows per-particle colour. For millions of particles, use GPU simulation via GPGPU (Section 12h).

Raycaster

Raycaster - Mouse Picking & Interaction

Cast a mathematical ray from the camera through the mouse pointer into the scene. raycaster.setFromCamera(pointer, camera) then intersectObjects(meshArray) returns all hit objects sorted by distance, each with exact hit point, normal, UV, and face index. The foundation for all 3D clicking, hovering, and dragging.

Clipping Planes

Clipping Planes - Cross-Sections

Discard all fragments on one side of a mathematical plane (Plane: normal + constant). renderer.clippingPlanes clips globally. material.clippingPlanes clips per-material. Animate the plane to create a cutting animation. Multiple planes create complex cross-section views - medical, architectural, CAD visualisations.

16

Loaders

Loaders import external assets - 3D models, textures, environments. Three.js ships a base Loader class and dozens of format-specific loaders in the addons. Use GLTFLoader for 3D models - it's the "JPEG of 3D", compact and feature-complete. Use LoadingManager to track combined loading progress across all assets.

GLTF Loader

GLTFLoader - The Standard 3D Format

.gltf (JSON + separate .bin + images) or .glb (single binary bundle). Supports: PBR materials, skeletal animation, morph targets, multiple meshes/scenes, lights, cameras, custom extensions (KHR_draco_mesh_compression, KHR_materials_transmission, EXT_meshopt_compression). The correct default choice for web delivery.

FBX Loader

FBXLoader - Autodesk Format

Autodesk FBX is common in game pipelines from Maya, 3ds Max, MotionBuilder and game engines like Unity/Unreal (as export format). FBXLoader supports skeletal animation, morph targets, embedded textures. Files tend to be large - prefer exporting to GLTF from DCC tools where possible, using FBX only when needed.

OBJ Loader

OBJLoader - Universal Legacy Format

The most widely supported 3D format - almost every 3D application can export OBJ. Human-readable text format, paired with .mtl for materials (Phong, no PBR). No animation support. Large file sizes. Good for static geometry interchange and legacy assets. Use GLTF for anything new.

Draco Compression

Draco Compression

Google's open-source mesh compression codec reduces geometry file size by 50–90% with minimal visual loss. Embed in GLTF via KHR_draco_mesh_compression extension. Requires DRACOLoader with the decoder WASM loaded from a CDN or bundled. Worth the setup cost for bandwidth-critical apps.

HDR Loader

RGBELoader / EXRLoader - HDR Environments

Load .hdr (Radiance RGBE format) or .exr (OpenEXR) HDRI environment maps - equirectangular panoramas with high dynamic range. Pass the loaded texture to PMREMGenerator.fromEquirectangular() to prefilter for physically-based IBL. Free HDRI libraries: Poly Haven, HDRIHaven.

SVG Loader

SVGLoader - Vector Graphics in 3D

Parses SVG paths, circles, rects and polygons into Three.js ShapePaths. Pass shapes to ExtrudeGeometry for 3D logos with depth and bevel, or ShapeGeometry for flat vector art in 3D space. Preserves curves, fills and colours from the source SVG.

17

Physics

Three.js has no built-in physics - it's a rendering library. But it pairs seamlessly with dedicated physics engines. The pattern is always the same: physics world runs the simulation, Three.js mirrors the results visually. Popular choices: Rapier (Rust/WASM, fastest, deterministic), cannon-es (pure JS, easy), Ammo.js (Bullet port, full-featured), Jolt (game-quality).

Rigid Body

Rigid Body Physics

Objects with mass that fall, bounce, slide and collide realistically. Each body has a collision shape (box, sphere, convex hull, trimesh), mass (0 = static), friction and restitution (bounciness). Every frame: world.step(delta) → copy body.position to mesh.position, body.quaternion to mesh.quaternion.

Cloth Simulation

Cloth Simulation

A grid of particles connected by stretch, shear and bend spring constraints. Pin some particles (e.g. top corners) and let gravity pull the rest. Apply wind force for fabric movement. Resolve constraints iteratively each frame - more iterations = stiffer, more accurate. Ammo.js soft bodies or custom verlet integration.

Vehicle Physics

Vehicle Physics

Ray-cast vehicle model: a chassis rigid body with four ray-cast "wheels". Rays shoot downward from each wheel mount and detect the ground; suspension compresses based on contact distance. Engine torque applied to driven wheels; steering applies to front wheels. Rapier and Ammo.js both have vehicle controllers.

Constraints

Constraints & Ragdolls

Constraints join two rigid bodies with limits: Hinge (door, wheel), Slider (piston), Lock (weld), Point-to-point (wrecking ball chain), Cone-twist (shoulder joint with angle limits). Chain cone-twist constraints for a ragdoll skeleton that collapses physically when the character is knocked down.

18

Helpers & Debug Tools

Helpers are Object3D instances added to the scene during development to visualise invisible things - camera frustums, light shapes, bone positions, bounding boxes, normals. They are standard scene objects: add them, move them, set visible=false. Remove before shipping. Invaluable for debugging shadow cameras, verifying rig setup, checking frustum culling.

Grid and Axes Helpers

GridHelper + AxesHelper

GridHelper draws a flat grid at Y=0 - instantly orients you in 3D space. new GridHelper(size, divisions). AxesHelper draws the XYZ axes as red (X), green (Y), blue (Z) lines. new AxesHelper(length). These two together are the first thing to add to any new project.

Camera Helper

CameraHelper - Visualise Frustum

Renders the wireframe frustum of any camera as lines in the scene. Add new CameraHelper(camera) to visualise near plane, far plane and field of view. Critical when debugging shadow cameras (DirectionalLight.shadow.camera) - you can see exactly what the light "sees".

Light Helpers

Light Helpers

DirectionalLightHelper: arrow + target line. PointLightHelper: wireframe sphere at the light position. SpotLightHelper: cone shape. HemisphereLightHelper: two colour-coded hemispheres. RectAreaLightHelper: outlined rectangle. All update when you move the light. Pass size to control helper scale.

Skeleton Helper

SkeletonHelper - Bone Visualiser

Renders the bone hierarchy of a SkinnedMesh as coloured line segments showing each bone's position and length. new SkeletonHelper(skinnedMesh) - add it to the scene and it updates every frame. Essential for debugging animation rigs, verifying bone names and understanding skeleton hierarchy after loading a GLTF character.

19

Curves, Shapes & Extras

Three.js has a rich 2D/3D curve and shape system. Curves define smooth paths through space - use them for camera fly-throughs, tube geometry, spline animation. Shapes define 2D outlines that can be extruded into 3D. PMREMGenerator is the utility that makes physically-based environment lighting work correctly.

Bezier Curves

Bezier Curves

QuadraticBezierCurve3 (start, control, end) and CubicBezierCurve3 (start, control1, control2, end). Define smooth curves through 3D space using control points that pull the curve without it necessarily passing through them. curve.getPoints(n) samples N points - pass to TubeGeometry, LineGeometry, or use for animation paths.

CatmullRom Spline

CatmullRom Spline - Camera Paths

Unlike bezier curves, CatmullRomCurve3 passes through all control points. Perfect for cinematic camera fly-throughs: place a series of waypoints, sample curve.getPointAt(t) as t goes 0→1, set the camera to look at the next point on the curve for smooth forward-facing movement.

Shapes and Extrude

Shape + ExtrudeGeometry

Define a 2D outline with Shape (moveTo, lineTo, bezierCurveTo, arc, hole for cutouts). Pass to ShapeGeometry for flat 2D, or ExtrudeGeometry with depth and bevelSize parameters for 3D depth. Create custom logos, architectural mouldings, extruded text, custom mechanical parts.

PMREMGenerator

PMREMGenerator - Prefiltered Environment Maps

Pre-filters a raw environment (HDRI or cubemap) into a Prefiltered Mipmapped Radiance Environment Map (PMREM). Different mip levels correspond to different roughness values - a rough surface samples a blurry mip, a mirror samples the sharpest mip. Required for correct PBR rendering with environment lighting. Run once after loading the HDRI.

const pmrem = new THREE.PMREMGenerator( renderer );
const envMap = pmrem.fromEquirectangular( hdrTexture ).texture;
scene.environment = envMap;
20

Math Library

Three.js includes a complete 3D math library. These classes are used everywhere in the engine and in your code - setting positions, composing rotations, computing transforms, building ray queries. Understanding Vector3, Quaternion and Matrix4 deeply is fundamental to working with Three.js beyond the basics.

Three.js Math Library

Complete Math Library

Vector2/3/4 - 2D/3D/4D vectors. Operations: add, sub, multiply, divide, dot, cross, length, normalize, lerp, clone. The most used class in Three.js.

Quaternion - Rotation without gimbal lock. setFromEuler, setFromAxisAngle, slerp (smooth rotation interpolation). Always use Quaternion for rotation math - never Euler for interpolation.

Euler - Human-readable rotation angles (X, Y, Z in radians + order). Easy to set from degrees, but don't interpolate between Eulers - convert to Quaternion first.

Matrix3/4 - 3×3 and 4×4 matrices for transforms. Every Object3D has a matrix (local) and matrixWorld (world space). decompose extracts position/quaternion/scale.

Color - RGB + HSL colour. setHex, setHSL, lerp, convertLinearToSRGB. Always work in linear colour space internally.

Box3, Sphere - Bounding volumes. box.setFromObject(mesh) computes tight axis-aligned bounds. box.intersectsBox(other) for broad-phase collision.

Ray, Plane, Frustum, Triangle, Line3 - Geometric primitives for intersection testing, clipping, and spatial queries.

MathUtils - lerp, clamp, mapLinear, degToRad, radToDeg, smoothstep, randFloat, seededRandom, UUID.