graphics3d
three.js
a scene, a camera and a renderer, then meshes, lights, textures, models, picking and effects.
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
- 3d on a web page
- model and product viewers
- data in 3d
- small games and effects
on this page
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
- 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.
what trips people up:
- a change to
fov,aspect,nearorfarshows only aftercamera.updateProjectionMatrix().4 - flicker where two surfaces nearly touch, called z-fighting: the depth buffer’s precision is spread from
neartofar, finest close to the camera. setnearas far out, andfaras close in, as the scene allows.6 - a soft picture on a phone: the drawing buffer is in css pixels unless you scale it by
devicePixelRatio. that costs: a 3× screen draws 9 times the pixels. the figures here cap the ratio at 2.7
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.2,8
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.9,10
// 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.
what trips people up:
- a black mesh: lambert, phong, standard and physical need a light. standard and physical look their best with an environment map too, set on
scene.environmentor the material’senvMap.10 - a plane that vanishes when you look at it from behind: a material draws front faces only.
side: THREE.DoubleSidedraws both.9
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
- 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.
what trips people up:
- no shadow: one of the four switches is off. turning shadows on or off after the first frame also needs
material.needsUpdate = true, since a shadow map changes the shader.8 - a shadow cut off at an edge: it fell outside the shadow camera’s box. a bigger box spreads the same map over more ground, and the shadow turns blocky. a
CameraHelperonsun.shadow.cameradraws the box.13 - stripes or speckles on lit faces, called shadow acne: nudge
shadow.biasby around 0.0001, or raiseshadow.normalBias.15 - a directional light that won’t turn: it aims at
sun.target. move the target, and add it to the scene, or it stays put.16
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;
- 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.
what trips people up:
- washed-out colors: a color texture left at
NoColorSpaceis read as linear, so it comes out too light.18 repeatwith no tiling: past 1 it needsRepeatWrappingorMirroredRepeatWrapping. a wrap mode changed after the first draw also needstexture.needsUpdate = true, since it’s set on the gpu when the image uploads.repeatandoffsetdon’t: they reach the shader on every draw.19- gpu memory is the pixels, not the file: about width × height × 4 bytes, and a third more for the mipmaps. a 2048 × 2048 jpeg takes about 22 mb on the gpu, however small the file is.17
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.
what trips people up:
- damping on, but no
update()every frame: the view lags behind the drag and stops short when you let go.autoRotateneeds the loop too.21 camera.lookAtwhile the controls are on: the nextupdate()points the camera back atcontrols.target. move the target instead.21- on a phone the canvas takes every swipe: OrbitControls sets
touch-action: noneon it, so the page won’t scroll over it. leave room around it to scroll by.21 - the wheel zooms instead of scrolling the page, since the controls stop its scroll. this figure turns zoom on only after a click.21
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:
- a model you can’t see: it may be far too big (with the camera inside it) or too small, or sitting in the dark. the manual’s first checks: an
onErrorcallback to see the error, a light, and a scale up or down by 1000.24 - a model that loads but looks black: its materials are pbr, so they need light, and look best with an environment map.10
- images packed inside a
.glbload throughblob:urls, and a content security policy has to listblob:to allow them:'self'never matches one.25,26 this site’s policy doesn’t, so the house has no textures.
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.
what trips people up:
- the cost: past a bounding sphere test, the ray checks every triangle of every mesh you pass, on the cpu. pass only what can be picked, and
falseas the second argument when the children don’t matter.27,28 - hidden objects still get hit: the raycaster checks
layers, notvisible.27 - a face seen from behind isn’t hit.
side: THREE.DoubleSideon the material catches both sides.27
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
- 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.
what trips people up:
- instances that don’t move: after
setMatrixAtorsetColorAton a mesh that has been drawn, setinstanceMatrix.needsUpdateorinstanceColor.needsUpdatetotrue.30 - instances that vanish near the edge of the view: culling uses the mesh’s bounding sphere, worked out once, from the matrices it had on its first frame. call
computeBoundingSphere()after moving them.8,32
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)
- 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.
what trips people up:
- everything darker or lighter once the composer is in:
OutputPassis missing, or something converts to srgb twice. the composer’s targets hold linear color in half floats, and the canvas wants srgb.18,34 renderer.renderin the loop: it draws the scene straight to the screen and skips the passes. callcomposer.render().33- a blurry or stretched result after a resize: the composer keeps its own targets, so it needs its own
setSize.34
pitfalls
- nothing frees itself. removing a mesh from the scene leaves its geometry, material and textures on the gpu. call
dispose()on each when you’re done with it, and on render targets, controls and passes.renderer.info.memorycounts what’s still held.35 - too many canvases. chrome keeps 16 webgl contexts alive at once, 8 on android, and when a page makes one more, the oldest is lost.36 a page with many scenes can start each one near the viewport and drop it after, the way this one does:
renderer.dispose(), thenrenderer.forceContextLoss()to hand the context back right away.37 - colors that look off. three works in linear srgb and converts hex and css colors into it for you. textures and the output are yours to mark:
colorSpaceon color textures,renderer.outputColorSpacefor the canvas (srgb by default), andOutputPasswith a composer.18,3 - a loop that never stops.
setAnimationLoopdraws every frame, even when nothing moves. a scene that mostly sits still can draw on change instead, like the orbit controls code above, and spare the battery.22
sources
-
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. ↩
-
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
-
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)).
outputColorSpacestarts as srgb at line 312 (opens in a new tab). ↩ ↩2 -
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 insite/src/visuals/three/camera.test.ts. ↩ ↩2 -
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). ↩
-
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. ↩
-
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. ↩ -
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 = truewhen a texture or a shadow map appears or goes; textures needneedsUpdatewhen their image changes; a camera needsupdateProjectionMatrix()after fov, aspect, near or far change; and anInstancedMeshneeds its bounding box and sphere computed again aftersetMatrixAt(). ↩ ↩2 ↩3 -
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
sidedefaulting toTHREE.FrontSide. ↩ ↩2 -
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
-
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. ↩
-
PointLight.js (opens in a new tab) at r186: intensity in candela, a
distanceof 0 for no limit, and adecayof 2, inverse-square, which physically correct rendering should leave alone. SpotLight.js (opens in a new tab) takes the same, plus a coneangleof π/3 and apenumbraof 0. ↩ -
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;
CameraHelperon the shadow camera; and why a larger shadow area makes blockier shadows. ↩ ↩2 -
WebGLShadowMap.js (opens in a new tab) at r186: shadow maps start off, the type starts at
PCFShadowMap, andPCFSoftShadowMaplogs a warning and falls back to it. constants.js (opens in a new tab) marksPCFSoftShadowMapdeprecated since r186. ↩ -
LightShadow.js (opens in a new tab) at r186:
biasstarts at 0 and adjustments around 0.0001 may reduce artifacts;normalBiasreduces shadow acne, at the cost of some distortion;radiusabove 1 blurs shadow edges and has no effect withBasicShadowMap;mapSizeis 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 insite/src/visuals/three/lights.test.ts. ↩ ↩2 -
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. ↩
-
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.tsand checked in its test. ↩ ↩2 -
color management (opens in a new tab) in the three.js manual: the linear srgb working color space,
ColorManagementon by default and converting hex and css colors, color textures markedSRGBColorSpace, data textures left atNoColorSpace, the output color space andOutputPass, and what goes wrong when one is set wrong. ↩ ↩2 ↩3 ↩4 -
Texture.js (opens in a new tab) at r186:
wrapSandwrapT, andrepeat(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. ↩ -
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 toexamples/jsm/. ↩ -
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.dampingFactoris 0.05 (opens in a new tab).update()points the camera at the target (opens in a new tab), connecting the controls setstouch-action: none(opens in a new tab) on the canvas, and the wheel handler (opens in a new tab) callspreventDefault()while zoom is on. ↩ ↩2 ↩3 ↩4 ↩5 -
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’
changeevent, and the extra care damping needs. ↩ ↩2 -
the gltf 2.0 specification (opens in a new tab), at the khronos repo’s commit 1c84b58: what a
.gltf, its.binfiles 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 -
loading 3d models (opens in a new tab) in the three.js manual: gltf as the recommended format,
GLTFLoaderfrom the addons, and the troubleshooting list: log errors withonError, try a scale 1000 times up or down, and add a light. ↩ ↩2 -
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 toMeshPhysicalMaterial. it loads an image stored in a buffer view (opens in a new tab) through a blob url fromURL.createObjectURL. ↩ ↩2 -
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
blobscheme never matches'self'. ↩ -
Raycaster.js (opens in a new tab) at r186:
setFromCameratakes the point in normalized device coordinates, -1 to 1; the fields of a hit,instanceIdincluded; hits sorted nearest first; faces hit only from the front unless the material isDoubleSide; children checked unlessrecursiveis false; and the walk tests each object’slayers, with no check ofvisible. ↩ ↩2 ↩3 ↩4 -
raycast()in Mesh.js (opens in a new tab) at r186: a bounding sphere test, a bounding box test, then the geometry’s triangles. ↩ -
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. ↩
-
InstancedMesh.js (opens in a new tab) at r186: one geometry and material with many transforms, to cut draw calls; and
instanceMatrixandinstanceColorneedneedsUpdateaftersetMatrixAtandsetColorAt(opens in a new tab). ↩ ↩2 -
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. ↩
-
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. ↩ -
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 ofrenderer.render(), the last enabled pass drawn to the screen,RenderPassfirst andOutputPasslast for the srgb conversion and tone mapping. ↩ ↩2 -
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 -
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 havedispose()too, andrenderer.infocounts what’s held. ↩ -
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. ↩
-
webgl best practices (opens in a new tab) on mdn: lose contexts eagerly with
WEBGL_lose_contextonce you’re done with them. three’sforceContextLoss()(opens in a new tab) at r186 calls that extension. ↩