graphics3d

three.js

a scene, a camera and a renderer, then meshes, lights, textures, models, picking and effects.

report a mistake
.md

a renderer draws a scene through a camera. the scene is a tree of objects, and a mesh in it is a geometry with a material.

version
r186 three@0.186.1, what this page runs
axes
y up a camera looks down its own -z
cleanup
by hand dispose() what you made, or the gpu keeps it
draw calls
1 for thousands of copies of a mesh, instanced
reach for it
  • 3d on a web page
  • model and product viewers
  • data in 3d
  • small games and effects
on this page
  1. scene, camera, renderer
  2. geometry, material, mesh
  3. lights and shadows
  4. textures and uv
  5. orbit controls
  6. gltf loading
  7. raycasting
  8. instancing
  9. post-processing
  10. pitfalls
  11. sources

three.js is a javascript library for 3d in the browser. you build a scene out of objects, point a camera at it, and a renderer draws it into a canvas, with webgl or webgpu.1 this sheet runs r186, which is three@0.186.1 on npm. every figure is a live scene: it starts when you scroll to it, draws only when you change something, and frees its gpu memory when you scroll past.

the code blocks build on each other: canvas, renderer, scene and camera come from the first one.

scene, camera, renderer

it takes three things to draw anything: a Scene that holds what you draw, a camera that decides what part of it you see, and a renderer that draws the scene, as the camera sees it, into a canvas.2 WebGLRenderer draws with webgl 2: three dropped webgl 1 in r163.3

a PerspectiveCamera sees the way an eye does: far things look smaller. it takes four numbers. fov is the vertical angle it takes in, in degrees. aspect is the canvas’s width over its height. anything closer than near or past far isn’t drawn. leave them out and you get 50, 1, 0.1 and 2000.4 a camera looks down its own -z axis, and +y is up.5

import * as THREE from 'three';

const canvas = document.querySelector('canvas');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
const scene = new THREE.Scene();
// fov, aspect, near, far
const camera = new THREE.PerspectiveCamera(50, 1, 0.1, 100);
camera.position.set(0, 1.5, 5); // up a little, and back along +z
camera.lookAt(0, 0.6, 0);

const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshNormalMaterial(),
);
cube.position.y = 0.6;
scene.add(cube);

// the canvas's css size sets the picture's size. keep the two in step
new ResizeObserver(() => {
  const { clientWidth: width, clientHeight: height } = canvas;
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.setSize(width, height, false); // false: leave the css size alone
  camera.aspect = width / height;
  camera.updateProjectionMatrix(); // fov, aspect, near, far apply after this
}).observe(canvas);

renderer.setAnimationLoop((time) => {
  cube.rotation.y = time / 1000; // radians
  renderer.render(scene, camera);
});

setAnimationLoop calls you once per screen refresh, and pauses while the tab is hidden.2

50°
5.0
height at the box
4.66
width at the box
7.46
near, far
0.1, 100

a live three.js scene: a cyan box in front, an amber box behind it on the left and a grey box far back on the right, on a grid. two sliders set the camera's field of view, from 10 to 120 degrees, and its distance from the cyan box, from 2 to 12. a readout gives the height and width of the view at the cyan box, 4.66 by 7.46 at the start (a 50 degree fov from 5 away), and the camera's near and far planes, 0.1 and 100.

the view at the cyan box is 2 × distance × tan(fov ÷ 2) tall. get the same height twice, with a wide fov up close and a narrow one far back: the cyan box looks the same both times, and the boxes behind it shrink much less with the narrow one.

what trips people up:

geometry, material, mesh

a Mesh is a geometry and a material. the geometry is the shape: vertex positions, normals and uvs, kept in typed arrays on a BufferGeometry. the built-in ones, like BoxGeometry and SphereGeometry, fill those in for you. the material is how the surface looks, and how it takes light.28

the mesh materials, fastest first: MeshBasicMaterial ignores lights. MeshLambertMaterial takes light, with no shine. MeshPhongMaterial adds a highlight. MeshStandardMaterial is physically based, set by roughness and metalness, which start at 1 and 0: fully rough, not metal. MeshPhysicalMaterial adds clearcoat, sheen, glass-like transmission and more, at more cost per pixel. MeshNormalMaterial colors each point by the way its surface faces.910

// radius, then segments around and from top to bottom
const geometry = new THREE.SphereGeometry(1, 32, 16);
const material = new THREE.MeshStandardMaterial({
  color: 0x22d3ee,
  roughness: 0.4,
});
const ball = new THREE.Mesh(geometry, material);
ball.position.set(-1.5, 1, 0);
ball.rotation.y = Math.PI / 4; // rotations are in radians
ball.scale.setScalar(0.5);
scene.add(ball);

// meshes can share a geometry and a material
const twin = new THREE.Mesh(geometry, material);
twin.position.set(1.5, 1, 0);
scene.add(twin);
vertices
24
triangles
12
lights
used

physically based: roughness and metalness decide how it reflects the lights.

a live three.js scene with one cyan mesh over a grid. one menu picks its geometry: a box, a 32 by 16 sphere, a cone, a torus knot or a plane. another picks its material: standard, lambert, basic, normal or wireframe. a readout counts the geometry's vertices and triangles, 24 and 12 for the box and 561 and 960 for the sphere, and says whether the material uses the scene's lights. a line under it says what the material does.

a box has 8 corners but 24 vertices: each face gets its own four, so each face keeps its own normal. basic and normal look the same with the lights on or off.

what trips people up:

lights and shadows

lights reach the lit materials only. AmbientLight lights everything evenly, from no direction. HemisphereLight fades from a sky color above to a ground color below. DirectionalLight is the sun: parallel rays, aimed from its position at its target. PointLight is a bulb, SpotLight a cone, and RectAreaLight a glowing rectangle that works with standard and physical materials only and casts no shadow.11 point and spot lights fade with the square of the distance (decay is 2), and their intensity is in candela.12

shadows take four switches: the renderer’s shadow map, the light, and each mesh that casts or receives one. for every light that casts shadows, three draws the shadow casters again from the light’s point of view, into a depth texture called the shadow map, then checks each pixel of the real frame against it. a point light takes six of those passes, one per direction. only directional, point and spot lights cast shadows.13

renderer.shadowMap.enabled = true; // off by default
renderer.shadowMap.type = THREE.PCFShadowMap; // the default: filtered edges

const floor = new THREE.Mesh(
  new THREE.PlaneGeometry(10, 10),
  new THREE.MeshStandardMaterial(),
);
floor.rotation.x = -Math.PI / 2; // a plane starts upright, facing +z
floor.receiveShadow = true;
scene.add(floor);
ball.castShadow = true;

const sun = new THREE.DirectionalLight(0xffffff, 2.5);
sun.position.set(3, 5, 4); // it shines from here toward sun.target, at the origin
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024); // 512 × 512 by default
// the shadow box starts -5 to 5 across, 0.5 to 500 deep. fit it to the scene
const box = sun.shadow.camera;
box.left = box.bottom = -4;
box.right = box.top = 4;
box.far = 20;
sun.shadow.bias = -0.0005; // moves the depth test a little, against shadow acne
scene.add(sun, new THREE.AmbientLight(0xffffff, 0.3));
scene.add(new THREE.CameraHelper(box)); // draws the box, to see what it covers

the other types are BasicShadowMap, unfiltered, and VSMShadowMap. PCFSoftShadowMap is deprecated in r186: three warns and uses PCFShadowMap.14 shadow.radius above 1 softens the edges of pcf and vsm shadows, and does nothing to basic ones.15

40°
shadow map
512 × 512
shadow camera
10 × 10, 0.5 to 500
radius
4
bias
-0.0005

a live three.js scene: a cyan box, an amber ball and a grey ring on a dark floor, lit by one directional light that casts shadows. a helper draws the light as a small amber square with a line to its target, the middle of the floor. a slider sets the sun's height, from 8 to 85 degrees above the floor. a menu sets the renderer's shadow map type: off, basic, pcf (the default) or vsm. a readout lists the shadow map's size, 512 by 512, and the shadow camera's box, 10 by 10 and 0.5 to 500 deep, which are three's defaults, and the figure's own radius, 4, and bias, -0.0005.

the amber line runs from the light to its target. a low sun stretches the shadows. basic draws hard, jagged edges. pcf and vsm soften them by shadow.radius, 4 here, which basic ignores.

what trips people up:

textures and uv

a texture is an image the gpu samples while it draws. each vertex carries a uv coordinate that says where in the image it lands: u runs left to right and v bottom to top, both 0 to 1 across the image. the built-in geometries come with uvs.17

TextureLoader loads an image. a CanvasTexture reads a canvas you draw on, and a DataTexture takes raw numbers. an image of colors holds srgb values, so mark it: colorSpace = THREE.SRGBColorSpace. textures that hold data, like normal and roughness maps, keep the default, NoColorSpace.18

// returns at once. the image fills in when it arrives
const bricks = new THREE.TextureLoader().load('/textures/bricks.jpg');
bricks.colorSpace = THREE.SRGBColorSpace; // an image of colors
bricks.wrapS = bricks.wrapT = THREE.RepeatWrapping; // the default clamps
bricks.repeat.set(4, 4); // uv runs 0 to 4: four copies each way
bricks.anisotropy = renderer.capabilities.getMaxAnisotropy(); // sharper at a slant
floor.material.map = bricks;
floor.material.needsUpdate = true; // a new map changes the shader

// any canvas can be a texture
const paper = document.createElement('canvas');
paper.width = paper.height = 256;
const ctx = paper.getContext('2d');
ctx.fillStyle = '#22d3ee';
ctx.fillRect(0, 0, 128, 128);
const drawn = new THREE.CanvasTexture(paper);
drawn.colorSpace = THREE.SRGBColorSpace;
// after drawing on the canvas again:
drawn.needsUpdate = true;
1 × 1
uv on the square
0 to 1
wrapS, wrapT
ClampToEdge
image
256 × 256 canvas

uv runs 0 to 1 across the square, so the image shows once. flipY is on: uv 0,0 is its bottom-left.

a live three.js scene: a texture drawn on a 256 pixel canvas, a dark checkerboard with a cyan u axis along the bottom, an amber v axis up the left and the corners labelled 0,0 to 1,1, mapped onto a tilted square. the canvas itself shows in the corner. a slider sets repeat from 1 to 4 and a menu sets the wrap mode: clamp to edge (the default), repeat or mirrored repeat. at repeat 1 the image shows once, with uv 0,0 at its bottom-left. past 1, clamp smears the edge pixels, repeat starts the image over, and mirrored repeat flips every other copy.

the inset is the canvas the texture reads. past repeat 1, the uvs on the square run past 1, and the wrap mode decides what shows out there.

what trips people up:

orbit controls

OrbitControls moves a camera around a target point as you drag. it’s an addon, so it comes from three/addons/, not three.20 one finger or the left button orbits, the wheel or a pinch zooms, and the right button, two fingers or the arrow keys pan. the camera’s up stays up.21

it moves the camera and nothing else: something still has to draw. a loop works, or a render on each change event, so nothing runs while the view sits still.22

import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.6, 0); // the point it circles, the origin by default
controls.minDistance = 2;
controls.maxDistance = 12;
controls.maxPolarAngle = Math.PI / 2; // no lower than level: above the floor
controls.listenToKeyEvents(window); // arrow keys pan
controls.update(); // after any change made in code

// draw on demand: no loop, a frame when the view changes
renderer.setAnimationLoop(null);
controls.addEventListener('change', () => renderer.render(scene, camera));
renderer.render(scene, camera);

damping lets the view coast after you let go, so update() has to run every frame:

controls.enableDamping = true; // dampingFactor is 0.05
renderer.setAnimationLoop(() => {
  controls.update();
  renderer.render(scene, camera);
});
distance
5.50
azimuth
32°
polar
62°

loading the model.

a live three.js scene: the site's own small gltf house, with grey walls, an amber roof and a cyan door, on a grid, loaded with GLTFLoader. drag to orbit it, click it and scroll or pinch to zoom, use the arrow keys to pan, and shift with the arrows to orbit. a damping button lets the view coast after you let go, and is off under reduced motion. reset view goes back to the start. a readout gives where the camera sits around the house: 5.5 away, 32 degrees around and 62 degrees down from straight above, at the start. a line under it gives the file's size and what it loaded as.

the readout is where the camera sits around its target, the way OrbitControls keeps it: how far, how far around, and how far down from straight above.

what trips people up:

gltf loading

gltf is the khronos group’s format for 3d scenes, made for loading at runtime. a .gltf file is json, with the binary data in .bin files beside it or inside the json as base64 data uris, which take about a third more bytes. a .glb packs the json and the binary data into one file: a 12-byte header, a json chunk and a binary chunk.23 three’s manual recommends gltf over the other formats.24

the json is a tree of indices. a scene lists nodes, a node holds a transform and a mesh, a mesh is a list of primitives, and a primitive points at accessors for its positions, normals and indices. an accessor reads typed numbers out of a buffer view, a slice of a buffer. lengths are in meters, +y is up, and the front of a model faces +z. materials are pbr metallic-roughness.23 GLTFLoader makes them MeshStandardMaterial, or MeshPhysicalMaterial when an extension adds clearcoat, transmission and the like.25

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const gltf = await new GLTFLoader().loadAsync('/models/house.glb');
scene.add(gltf.scene); // a Group: the file's nodes, meshes and materials

gltf.scene.traverse((object) => {
  if (object.isMesh) object.castShadow = true; // meshes cast no shadow until asked
});
// gltf.animations holds the clips for an AnimationMixer, gltf.cameras the cameras

the house in the orbit figure is the site’s own. site/scripts/make-house.mjs writes it from a tested module: three primitives (walls, roof and door), 30 vertices and 16 triangles in one 816-byte buffer, no textures. house.glb is 2,668 bytes. the same model as readable json, with the buffer as a data uri, is house.gltf, 4,569 bytes.

what trips people up:

raycasting

a Raycaster sends a ray from the camera through a point on the screen and lists what it hits, nearest first. the point goes in normalized device coordinates: -1 to 1 across the canvas on both axes, with y up, the other way from the page’s y. each hit has the object, its distance from the camera, the point in world space, the face and its uv, and an instanceId for an InstancedMesh.27

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();

canvas.addEventListener('pointerdown', (event) => {
  const rect = canvas.getBoundingClientRect(); // the canvas, not the window
  pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; // y flips
  raycaster.setFromCamera(pointer, camera);
  const [hit] = raycaster.intersectObjects([ball, twin, floor]); // nearest first
  if (hit) console.log(hit.object, hit.distance, hit.point);
});
pointer (ndc)
0.00, 0.00
hit
–
distance
–
point
–

tap a cube. or focus the figure, move the crosshair with the arrow keys, and press enter.

a live three.js scene: nine grey cubes in a three by three grid, seen from above and in front. tap or click the scene, or focus it, move the crosshair with the arrow keys and press enter, and a ray goes from the camera through that point. the first cube it hits turns amber. a readout gives the point in normalized device coordinates, the cube's name, the distance from the camera to the hit and the point it hit.

between the cubes the ray hits nothing: the floor grid isn't on the list it checks.

what trips people up:

instancing

every mesh is at least one draw call, a request from the cpu to the gpu, and each one costs something however small the mesh.29 an InstancedMesh draws many copies of one geometry with one material in one call. each copy gets its own matrix, and its own color if you set one.30 a BatchedMesh does the same for different geometries that share a material.31

const count = 1000;
const boxes = new THREE.InstancedMesh(
  new THREE.BoxGeometry(0.1, 0.1, 0.1),
  new THREE.MeshStandardMaterial(),
  count,
);
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
for (let i = 0; i < count; i++) {
  const [col, row] = [i % 32, Math.floor(i / 32)]; // a 32-wide grid
  matrix.makeTranslation(col * 0.2 - 3.1, 0.05, row * 0.2 - 3.1);
  boxes.setMatrixAt(i, matrix);
  boxes.setColorAt(i, color.setHSL(i / count, 0.7, 0.6));
}
scene.add(boxes); // a thousand boxes, one draw call

// moving one later
boxes.setMatrixAt(7, matrix.makeTranslation(0, 1, 0));
boxes.instanceMatrix.needsUpdate = true;
boxes.computeBoundingSphere(); // culling and raycasting read it
1,000
boxes drawn
1,000
draw calls
–
triangles
–
render() time
–

one draw call draws every box, and the grid is one more. the matrices went to the gpu once.

a live three.js scene: small boxes in a sunflower spiral on a grid, colored from cyan in the middle to blue at the edge. a slider sets how many, from 100 to 10,000, and the camera backs away as the spiral grows. a menu draws them as one InstancedMesh or as one Mesh each, which stops at 3,000. a readout counts the boxes, the draw calls and the triangles the renderer reports, and times one render() call. instanced, every count is 2 draw calls: the boxes and the grid. as separate meshes it is one call per box, plus the grid.

the time is how long one render() call takes here, on this device, so it changes from run to run. the draw calls don't.

what trips people up:

post-processing

post-processing draws the scene into a render target, an image on the gpu, then runs passes over that image, and the last one draws to the screen. EffectComposer holds the chain: a RenderPass first to draw the scene, then the effects, then OutputPass, which applies tone mapping and converts to srgb. passes run in the order you add them.33

import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';

renderer.toneMapping = THREE.ACESFilmicToneMapping; // bloom needs tone mapping on
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
const size = renderer.getSize(new THREE.Vector2());
// strength, radius, threshold
composer.addPass(new UnrealBloomPass(size, 0.8, 0.2, 0.8));
composer.addPass(new OutputPass()); // tone mapping and srgb, last

// composer.render, not renderer.render
renderer.setAnimationLoop(() => composer.render());
// on resize, after the renderer's own setSize: composer.setSize(width, height)
0.8
passes
3
tone mapping
ACES filmic

RenderPass → UnrealBloomPass → OutputPass

a live three.js scene: a cyan torus knot lit by one light, and two balls that glow, amber and white, on a grid, drawn through an EffectComposer. a menu picks the effect: bloom, pixelate or none. bloom has a strength slider from 0 to 3, and pixelate a pixel size slider from 1 to 16. a line under it lists the passes in order, like RenderPass, UnrealBloomPass, OutputPass. the balls are brighter than the bloom threshold and glow, and the lit knot isn't and doesn't.

bloom spreads light from what's brighter than its threshold: the balls glow, the lit knot doesn't. the pixelated pass draws the scene itself, at low resolution, so it takes the render pass's place.

what trips people up:

pitfalls

sources

  1. the three.js readme (opens in a new tab) at r186: a general-purpose 3d library whose builds include a webgl and a webgpu renderer, with svg and css3d renderers as addons. the package.json (opens in a new tab) at the same tag is version 0.186.1. ↩

  2. creating a scene (opens in a new tab) in the three.js manual: the scene, the camera and the renderer, a mesh as a geometry with a material applied, and an animation loop that draws on every screen refresh and pauses when you switch tabs. ↩ ↩2 ↩3

  3. WebGLRenderer.js (opens in a new tab) at r186: it draws with webgl 2, and webgl 1 isn’t supported since r163 (the error at line 102 (opens in a new tab)). outputColorSpace starts as srgb at line 312 (opens in a new tab). ↩ ↩2

  4. PerspectiveCamera.js (opens in a new tab) at r186: the defaults, fov 50, aspect 1, near 0.1 and far 2000, the vertical fov in degrees (opens in a new tab), and updateProjectionMatrix() (opens in a new tab), which must be called after any change to the camera’s settings. the 4.66 and 7.46 in the figure are checked in site/src/visuals/three/camera.test.ts. ↩ ↩2

  5. Camera.js (opens in a new tab) at r186: a camera looks down its local negative z axis. Object3D.js (opens in a new tab): the default up for objects is (0, 1, 0). ↩

  6. cameras (opens in a new tab) in the three.js manual: the gpu’s depth precision is spread between near and far, fine near the camera and coarse far away, z fighting when there isn’t enough, and choosing near and far to fit the scene. ↩

  7. responsive design (opens in a new tab) in the three.js manual, on hd-dpi displays: css pixels, a 3× phone drawing 9 times the pixels, and scaling the drawing buffer by devicePixelRatio. ↩

  8. how to update things (opens in a new tab) in the three.js manual: geometry data lives in typed arrays; after the first render, a material needs needsUpdate = true when a texture or a shadow map appears or goes; textures need needsUpdate when their image changes; a camera needs updateProjectionMatrix() after fov, aspect, near or far change; and an InstancedMesh needs its bounding box and sphere computed again after setMatrixAt(). ↩ ↩2 ↩3

  9. materials (opens in a new tab) in the three.js manual: the mesh materials from fastest to slowest (basic, lambert, phong, standard, physical), basic not affected by lights, and side defaulting to THREE.FrontSide. ↩ ↩2

  10. the class notes at r186: MeshLambertMaterial (opens in a new tab) is for non-shiny surfaces, without specular highlights. MeshPhongMaterial (opens in a new tab) adds them. MeshStandardMaterial (opens in a new tab) is physically based and does best with an environment map, and its roughness and metalness (opens in a new tab) start at 1 and 0. MeshPhysicalMaterial (opens in a new tab) adds clearcoat, sheen, transmission and more, costs more per pixel, and also wants an environment map. MeshNormalMaterial (opens in a new tab) maps normals to rgb colors. ↩ ↩2 ↩3

  11. lights (opens in a new tab) in the three.js manual, and the class notes at r186: AmbientLight (opens in a new tab), HemisphereLight (opens in a new tab), DirectionalLight (opens in a new tab), SpotLight (opens in a new tab) and RectAreaLight (opens in a new tab): no shadows and pbr materials only. ↩

  12. PointLight.js (opens in a new tab) at r186: intensity in candela, a distance of 0 for no limit, and a decay of 2, inverse-square, which physically correct rendering should leave alone. SpotLight.js (opens in a new tab) takes the same, plus a cone angle of π/3 and a penumbra of 0. ↩

  13. shadows (opens in a new tab) in the three.js manual: every light that casts shadows draws the casters from its own point of view, a point light six times; the three lights that can cast shadows; the renderer, light and mesh switches; CameraHelper on the shadow camera; and why a larger shadow area makes blockier shadows. ↩ ↩2

  14. WebGLShadowMap.js (opens in a new tab) at r186: shadow maps start off, the type starts at PCFShadowMap, and PCFSoftShadowMap logs a warning and falls back to it. constants.js (opens in a new tab) marks PCFSoftShadowMap deprecated since r186. ↩

  15. LightShadow.js (opens in a new tab) at r186: bias starts at 0 and adjustments around 0.0001 may reduce artifacts; normalBias reduces shadow acne, at the cost of some distortion; radius above 1 blurs shadow edges and has no effect with BasicShadowMap; mapSize is 512 by 512. DirectionalLightShadow.js (opens in a new tab) makes its camera an orthographic box from -5 to 5, 0.5 to 500 deep. these defaults are checked in site/src/visuals/three/lights.test.ts. ↩ ↩2

  16. DirectionalLight.js (opens in a new tab) at r186: the light points from its position to its target, rotating it does nothing, and the target has to be in the scene for a new position to count. ↩

  17. textures (opens in a new tab) in the three.js manual: loading, memory use of about width × height × 4 × 1.33 bytes, mipmaps and filtering, and repeating, offsetting and wrapping. the 22 mb is computed in site/src/visuals/three/uv-grid.ts and checked in its test. ↩ ↩2

  18. color management (opens in a new tab) in the three.js manual: the linear srgb working color space, ColorManagement on by default and converting hex and css colors, color textures marked SRGBColorSpace, data textures left at NoColorSpace, the output color space and OutputPass, and what goes wrong when one is set wrong. ↩ ↩2 ↩3 ↩4

  19. Texture.js (opens in a new tab) at r186: wrapS and wrapT, and repeat (opens in a new tab), which needs a repeating wrap mode past 1. WebGLTextures.js (opens in a new tab) sets the wrap mode only while it uploads the texture, which happens when its version changes, and WebGLMaterials.js (opens in a new tab) copies repeat and offset into the shader on every draw. ↩

  20. installation (opens in a new tab) in the three.js manual: the addons (controls, loaders, post-processing) are imported from three/addons/, which the package.json (opens in a new tab) maps to examples/jsm/. ↩

  21. OrbitControls.js (opens in a new tab) at r186: the mouse, touch and key gestures, up staying up, update() after any change to the camera made in code, and every frame with damping or autorotate on. dampingFactor is 0.05 (opens in a new tab). update() points the camera at the target (opens in a new tab), connecting the controls sets touch-action: none (opens in a new tab) on the canvas, and the wheel handler (opens in a new tab) calls preventDefault() while zoom is on. ↩ ↩2 ↩3 ↩4 ↩5

  22. rendering on demand (opens in a new tab) in the three.js manual: why a scene that doesn’t animate shouldn’t draw continuously, a render on the controls’ change event, and the extra care damping needs. ↩ ↩2

  23. the gltf 2.0 specification (opens in a new tab), at the khronos repo’s commit 1c84b58: what a .gltf, its .bin files and a glb hold (lines 417 to 426); base64 data urls a third longer than the bytes (line 558); the right-handed axes, +y up with the front facing +z, and lengths in meters (lines 755 to 764); scenes and nodes (from line 778), buffers, buffer views and accessors (from 993), meshes and their primitives (from 1590) and metallic-roughness materials (from 2618); and the glb container, a 12-byte header, then a json chunk and a binary chunk, each padded to 4 bytes (lines 3375 to 3480). ↩ ↩2

  24. loading 3d models (opens in a new tab) in the three.js manual: gltf as the recommended format, GLTFLoader from the addons, and the troubleshooting list: log errors with onError, try a scale 1000 times up or down, and add a light. ↩ ↩2

  25. GLTFLoader.js (opens in a new tab) at r186 makes its materials MeshStandardMaterial, and a material extension (opens in a new tab) like clearcoat switches one to MeshPhysicalMaterial. it loads an image stored in a buffer view (opens in a new tab) through a blob url from URL.createObjectURL. ↩ ↩2

  26. the content security policy level 3 (opens in a new tab) working draft of 27 october 2026, section 6.7.2.8: a url with the blob scheme never matches 'self'. ↩

  27. Raycaster.js (opens in a new tab) at r186: setFromCamera takes the point in normalized device coordinates, -1 to 1; the fields of a hit, instanceId included; hits sorted nearest first; faces hit only from the front unless the material is DoubleSide; children checked unless recursive is false; and the walk tests each object’s layers, with no check of visible. ↩ ↩2 ↩3 ↩4

  28. raycast() in Mesh.js (opens in a new tab) at r186: a bounding sphere test, a bounding box test, then the geometry’s triangles. ↩

  29. optimize lots of objects (opens in a new tab) in the three.js manual: every mesh is one or more requests to draw, and drawing two things has more overhead than drawing one. ↩

  30. InstancedMesh.js (opens in a new tab) at r186: one geometry and material with many transforms, to cut draw calls; and instanceMatrix and instanceColor need needsUpdate after setMatrixAt and setColorAt (opens in a new tab). ↩ ↩2

  31. BatchedMesh.js (opens in a new tab) at r186: many objects with one material but different geometries, drawn with multi-draw to cut draw calls. ↩

  32. intersectsObject() in Frustum.js (opens in a new tab) at r186 computes an object’s bounding sphere only when it has none yet, then tests that sphere. ↩

  33. how to use post processing (opens in a new tab) in the three.js manual: render to a render target, passes in the order they’re added, composer.render() in place of renderer.render(), the last enabled pass drawn to the screen, RenderPass first and OutputPass last for the srgb conversion and tone mapping. ↩ ↩2

  34. EffectComposer.js (opens in a new tab) at r186 makes its two targets at the canvas size times the pixel ratio, in half floats, and setSize() (opens in a new tab) resizes them and every pass. OutputPass.js (opens in a new tab) adds tone mapping and the color space conversion, and UnrealBloomPass.js (opens in a new tab) needs tone mapping on and takes strength, radius and threshold. ↩ ↩2

  35. how to dispose of objects (opens in a new tab) in the three.js manual: geometries, materials, textures and render targets keep their gpu side until dispose(), removing a mesh doesn’t dispose of anything, controls and passes have dispose() too, and renderer.info counts what’s held. ↩

  36. chromium at commit 509a17e: webgraphicscontext3d_provider_impl.cc (opens in a new tab), lines 121 to 127, sets the limit to 16 active webgl contexts, 8 on android, and webgl_rendering_context_base.cc (opens in a new tab), lines 499 to 513, loses the oldest one with a warning when a new one would pass it. ↩

  37. webgl best practices (opens in a new tab) on mdn: lose contexts eagerly with WEBGL_lose_context once you’re done with them. three’s forceContextLoss() (opens in a new tab) at r186 calls that extension. ↩