The Render Loop & Resizing
A game redraws the scene many times per second. In Three.js you hand the renderer a function and it calls it once per display frame:
renderer.setAnimationLoop((time) => {
update(); // move things
renderer.render(scene, camera); // draw
});
renderer.setAnimationLoop(null); // stop the loopsetAnimationLoop is a thin wrapper around requestAnimationFrame, with two advantages: it keeps working in WebXR sessions (where the headset, not the window, decides the frame timing), and null stops it cleanly. time is in milliseconds since the page started, like the requestAnimationFrame timestamp.
Delta time with THREE.Timer
The callback runs at the display's refresh rate: 60 Hz on many laptops, 120 Hz on many phones, 144 Hz or more on gaming monitors, and less when the device is busy. Moving something a fixed amount per frame makes the game speed depend on the screen. Multiply speeds by the time since the last frame (delta time) instead.
THREE.Timer measures it. Call timer.update(time) once per frame, then read getDelta() (seconds since the previous update) and getElapsed() (seconds since the start) as often as you like; they don't change until the next update. (Older code uses THREE.Clock, deprecated since r183.)
In this scene, the left cube turns a fixed 0.02 rad per frame, the right one 1.2 rad per second. On a 60 Hz display they match; on a faster display the left one spins faster. The "slow down" button simulates a struggling device by skipping frames:
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
button { position: fixed; left: 8px; top: 8px; font: 13px system-ui, sans-serif }
#info { position: fixed; right: 10px; top: 10px; color: #fff; font: 13px ui-monospace, monospace }</style>
<button id="slow">Slow down: off</button><div id="info"></div>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#151a26');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 1, 6);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight('#fff', '#335', 1.5));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(2, 3, 4);
scene.add(sun);
const perFrame = new THREE.Mesh(new THREE.BoxGeometry(1.2, 1.2, 1.2), new THREE.MeshStandardMaterial({ color: '#ef5350' }));
const perSecond = new THREE.Mesh(new THREE.BoxGeometry(1.2, 1.2, 1.2), new THREE.MeshStandardMaterial({ color: '#66bb6a' }));
perFrame.position.x = -1.5;
perSecond.position.x = 1.5;
scene.add(perFrame, perSecond);
const timer = new THREE.Timer();
timer.connect(document); // ignore the time while the tab is hidden
let slow = false, frame = 0;
document.getElementById('slow').onclick = (e) => { slow = !slow; e.target.textContent = `Slow down: ${slow ? 'on' : 'off'}`; };
const info = document.getElementById('info');
renderer.setAnimationLoop((time) => {
frame++;
if (slow && frame % 4) return; // pretend only every 4th frame arrives
timer.update(time);
const dt = Math.min(timer.getDelta(), 0.1); // clamp: a long pause must not teleport things
perFrame.rotation.y += 0.02; // per frame: speed depends on the frame rate
perSecond.rotation.y += 1.2 * dt; // per second: same speed everywhere
info.textContent = `dt ${(dt * 1000).toFixed(1)} ms elapsed ${timer.getElapsed().toFixed(1)} s`;
renderer.render(scene, camera);
});
</script>With "slow down" on, the red cube crawls at a quarter of its speed while the green one keeps its pace by taking bigger steps. Two details in the loop matter in every game:
- Clamp
dt. After a breakpoint, a tab switch or a long load,dtcan be seconds long; a character movingspeed * dtwould jump through walls.Math.min(dt, 0.1)caps it. timer.connect(document)uses the Page Visibility API so time spent in a hidden tab is not reported as one giant delta.
Fixed steps for gameplay and physics
Delta time keeps speeds right, but a simulation still behaves slightly differently with different step sizes (a jump peaks at a different height at 30 and 144 FPS, and collisions can be missed with big steps). Games therefore run gameplay and physics at a fixed step, usually 1/60 s, and render as often as the screen allows. The loop collects real time in an accumulator and runs as many fixed updates as fit:
// Fixed-step updates driven by irregular frame times (in seconds).
const STEP = 1 / 60;
let acc = 0, updates = 0, simTime = 0;
const frameTimes = [0.016, 0.017, 0.033, 0.008, 0.008, 0.050, 0.016];
for (const dt of frameTimes) {
acc += Math.min(dt, 0.1);
let n = 0;
while (acc >= STEP) { simTime += STEP; acc -= STEP; n++; updates++; }
const alpha = acc / STEP; // how far we are into the next step (for interpolation)
console.log(`frame ${(dt * 1000).toFixed(0).padStart(2)} ms -> ${n} update(s), alpha ${alpha.toFixed(2)}`);
}
console.log(`${updates} updates, simulated ${simTime.toFixed(3)} s`);frame 16 ms -> 0 update(s), alpha 0.96
frame 17 ms -> 1 update(s), alpha 0.98
frame 33 ms -> 2 update(s), alpha 0.96
frame 8 ms -> 1 update(s), alpha 0.44
frame 8 ms -> 0 update(s), alpha 0.92
frame 50 ms -> 3 update(s), alpha 0.92
frame 16 ms -> 1 update(s), alpha 0.88
8 updates, simulated 0.133 s
Frames of 16 ms run zero updates (16 ms is less than one 16.67 ms step), a 50 ms frame runs three, and the leftover time waits in the accumulator. The frames add up to 148 ms; the simulation advanced 133 ms (8 steps) and the remaining 15 ms (alpha 0.88 of a step) will be used next frame. Nothing is lost, and every update is exactly 1/60 s long, on every machine.
alpha tells you how far the real time is between the last simulated state and the next one. Because the picture can lag the simulation by up to one step, fixed-step games often interpolate when drawing: render each object at previous + (current − previous) · alpha. At 60 Hz updates the lag is small enough that many games skip this; on a 144 Hz monitor interpolation removes visible stutter. The play kit in this course uses a fixed 1/60 s step without interpolation, and the physics lessons pass the same step to the physics engine.
Resizing
When the window (or the playground frame) changes size, three things must follow it, or the picture is stretched or blurry:
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight; // 1. the camera's aspect ratio
camera.updateProjectionMatrix(); // 2. recompute its projection
renderer.setSize(innerWidth, innerHeight); // 3. the canvas and its drawing buffer
});Forgetting updateProjectionMatrix() is the most common mistake: changing fov, aspect, near, far or zoom only takes effect after it. If the canvas is not full-window (inside a page layout), watch the element instead with a ResizeObserver, and pass false as the third argument of setSize so Three.js does not overwrite your CSS size:
new ResizeObserver(([entry]) => {
const { width, height } = entry.contentRect;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false); // update the drawing buffer only
}).observe(container);devicePixelRatio and why to cap it
High-density screens have several device pixels per CSS pixel: devicePixelRatio is 2 on most phones and Retina laptops, and 3 or more on some phones. renderer.setPixelRatio(devicePixelRatio) makes the image sharp, but the GPU must shade ratio² times as many pixels:
// Pixels the GPU must shade per frame for a full-screen canvas.
const screens = [
['laptop 1440x900 @1', 1440, 900, 1],
['laptop 1440x900 @2', 1440, 900, 2],
['phone 390x844 @3', 390, 844, 3],
['phone 390x844 capped @2', 390, 844, 2],
];
for (const [name, w, h, ratio] of screens) {
const px = w * ratio * h * ratio;
console.log(`${name.padEnd(24)} ${(px / 1e6).toFixed(2).padStart(5)} Mpx (${(px * 60 / 1e6).toFixed(0)} Mpx/s at 60 fps)`);
}laptop 1440x900 @1 1.30 Mpx (78 Mpx/s at 60 fps)
laptop 1440x900 @2 5.18 Mpx (311 Mpx/s at 60 fps)
phone 390x844 @3 2.96 Mpx (178 Mpx/s at 60 fps)
phone 390x844 capped @2 1.32 Mpx (79 Mpx/s at 60 fps)
A phone at ratio 3 shades more than twice the pixels of the same phone at ratio 2, with a GPU much weaker than a laptop's, and the difference is hard to see. So every scene in this course starts with:
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));Games go further and pick the ratio from a quality setting, or lower it dynamically when the frame rate drops. Call setPixelRatio before setSize, or call setSize again after changing it.
Test yourself
Why multiply movement by dt?
- It makes rendering faster
- So speeds are per second and the game runs at the same pace on 60 Hz and 144 Hz displays
- WebGL requires it
- It removes the need for a fixed step
After a resize you set camera.aspect, but the image is still stretched. What did you forget?
renderer.render()camera.updateProjectionMatrix()scene.updateMatrixWorld()timer.update()
A phone has devicePixelRatio 3. Compared with capping it at 2, how many more pixels does the GPU shade at ratio 3?
- 1.5×
- 2.25×
- 3×
- 9×