You scroll, and the camera moves in on the subject. You stop, the picture settles a moment later; you scroll back, it goes back. This note covers how to build that by repainting a numbered sequence of still images on a canvas, rather than by scrubbing a video.
The sample below is the skeleton of what one of our own pages uses (245 frames, 1280×720, WebP, about 11.1 MB in total). It is a single file and runs without any image assets.
Three kinds of numbers appear in this article. To keep them apart:
- Measured: values from running the sample below in headless Chrome 158 on our Mac (table at the end)
- Calculated: values that come from a formula (the settle-time table)
- Our page's spec: frame count, size and weight (the one line above, nothing else)
Why not video.currentTime?
You can also rewrite a <video> element's currentTime as the page scrolls. But in a video compressed with inter-frame differences, showing the frame you jumped to may require decoding the frames around it. How much that stutters depends on the encoding settings and the device (this article does not measure the video approach).
In an image sequence every frame stands alone. You decide which frame to paint and call drawImage once. In exchange, three things are yours to decide:
- In what order to request hundreds of images
- What to paint when the frame you want has not arrived
- When to draw, and when to stop drawing
The whole sample
It draws 120 frames on the spot and turns them into images (on a real page frameUrl returns the URL of each numbered image). To stand in for network delay, each frame waits a random 0–400 ms.
<!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
html, body { margin: 0; background: #050409; }
#stage { height: 500vh; } /* scroll length = playback length */
canvas { position: sticky; top: 0; display: block; width: 100%; height: 100vh; height: 100dvh; }
</style>
<div id="stage"><canvas id="cv"></canvas></div>
<script>
const COUNT = 120;
const stage = document.getElementById('stage');
const cv = document.getElementById('cv');
const ctx = cv.getContext('2d', { alpha: false });
const imgs = new Array(COUNT);
const still = matchMedia('(prefers-reduced-motion: reduce)').matches;
const st = { p: 0, cur: 0, shown: -1, raf: 0, frames: 0, paints: 0 };
// Demo only: draw each frame on the spot. On a real page this returns the URL of frame i.
function frameUrl(i) {
const c = document.createElement('canvas'); c.width = 640; c.height = 360;
const g = c.getContext('2d'), k = i / (COUNT - 1);
g.fillStyle = '#050409'; g.fillRect(0, 0, 640, 360);
g.translate(320, 180); g.rotate(k * Math.PI * 1.5);
g.strokeStyle = '#F2F0EA'; g.lineWidth = 2;
for (let r = 0; r < 6; r++) { g.beginPath(); g.ellipse(0, 0, 40 + r * 22 + k * 60, 14 + r * 10, r * 0.5, 0, 6.2832); g.stroke(); }
return c.toDataURL('image/png');
}
// 1) Request order: every 8th frame and the last one first, the rest a moment later
function load(i) {
if (imgs[i]) return; // never start the same frame twice
const im = new Image(); im.decoding = 'async';
im.onload = () => { // repaint when a frame closer to the target than the one on screen arrives
const want = Math.round(st.cur);
if (st.shown < 0 || Math.abs(i - want) < Math.abs(st.shown - want)) kick();
};
imgs[i] = im;
setTimeout(() => { im.src = frameUrl(i); }, Math.random() * 400); // demo only: stands in for network delay
}
for (let q = 0; q < COUNT; q += 8) load(q);
load(COUNT - 1);
setTimeout(() => { for (let s = 4; s >= 1; s >>= 1) for (let i = 0; i < COUNT; i += s) load(i); }, 300);
// 2) A frame that has not arrived is replaced by the nearest one that has (returns its index, or -1)
const ready = (im) => im && im.complete && im.naturalWidth > 0;
function nearest(i) {
if (ready(imgs[i])) return i;
for (let d = 1; d < COUNT; d++) {
if (ready(imgs[i - d])) return i - d;
if (ready(imgs[i + d])) return i + d;
}
return -1;
}
// 3) Draw only while something is moving
function draw() {
st.raf = 0; st.frames++;
const target = st.p * (COUNT - 1);
st.cur = still ? target : st.cur + (target - st.cur) * 0.075; // keeps going a little after the hand stops
const n = nearest(Math.round(st.cur));
if (n >= 0) {
const im = imgs[n], W = cv.width, H = cv.height;
const s = Math.max(W / im.naturalWidth, H / im.naturalHeight); // same as object-fit: cover
const w = im.naturalWidth * s, h = im.naturalHeight * s;
ctx.drawImage(im, (W - w) / 2, (H - h) / 2, w, h);
st.shown = n; st.paints++;
}
if (Math.abs(target - st.cur) > 0.02) kick(); // caught up: do not ask for another frame
}
function kick() { if (!st.raf) st.raf = requestAnimationFrame(draw); }
// scroll position -> progress 0..1
function sync() {
const max = stage.offsetHeight - innerHeight;
st.p = max > 0 ? Math.max(0, Math.min(1, scrollY / max)) : 0;
kick();
}
function size() {
const dpr = Math.min(2, window.devicePixelRatio || 1);
cv.width = Math.max(2, Math.round(cv.clientWidth * dpr));
cv.height = Math.max(2, Math.round(cv.clientHeight * dpr));
sync();
}
new ResizeObserver(size).observe(cv);
addEventListener('scroll', sync, { passive: true });
addEventListener('pageshow', sync);
</script>
1. Request order: coarse over the whole range, then the rest
If you load from the first frame onward, someone who scrolls to the end during loading has no frame nearby. So the sample first starts 16 requests — every 8th frame (15 of them) plus the last one — and, 300 ms later, the rest (queued as every 4th, then every 2nd, then every frame). load never starts a frame twice, so however many times an index is asked for, its image is requested once.
You cannot fix the order of arrival (the wait is random in the sample, and real networks reorder too). What you fix is the order of asking. Once the coarse 16 are in, the page can show the whole range, start to end, in steps of 8 frames.
2. A frame that has not arrived is replaced by the nearest one
nearest(i) widens the search one step each way and returns the index of the closest frame that has arrived. Instead of a blank, the viewer keeps seeing a picture with a coarser step in time.
When an image arrives (onload), the sample checks whether it is closer than the frame on screen (st.shown) to the frame the follow is currently on (Math.round(st.cur)), and asks for a repaint if it is. When nothing is on screen yet (st.shown is -1), any frame is painted. A far-away arrival does not, by itself, ask for a repaint.
Measured: 120 ms after opening, 3–8 of the 120 frames had arrived and drawImage had run 2–3 times (six trials; the wait is random, so runs differ). In a run where frame 32 arrived before frame 0, frame 32 was shown first and was replaced as closer frames came in.
3. Draw only while something is moving
The requestAnimationFrame loop is not left running. kick() only asks for one draw at the next screen refresh, and draw() does not ask again once it has caught up with the target.
- scroll, resize, arrival of a closer frame →
kick() - distance to the target at or below 0.02 frames → no further request
Measured: counting for 2 seconds without touching anything, after loading and the first paints were done (from about 1.6 s after opening), there were 0 calls to draw and 0 drawImage calls. That is, while the page is still, this script issues no draw requests (power draw was not measured).
4. "A little further, then still" after the hand stops
Map the scroll position straight to a frame index and the picture jumps with every wheel notch. The sample moves the current frame st.cur toward the target by 7.5% per draw.
st.cur = st.cur + (target - st.cur) * 0.075;
The remaining distance is multiplied by 0.925 per draw, so from a distance of d frames the number of draws until it is at or below 0.02 is Math.ceil(Math.log(0.02 / d) / Math.log(0.925)) (calculated).
| Remaining distance | Draws until still | At 60 refreshes per second |
|---|---|---|
| 10 frames | 80 | about 1.3 s |
| 30 frames | 94 | about 1.6 s |
| 60 frames | 103 | about 1.7 s |
Measured: after 20 wheel notches 110 ms apart, the picture came to rest about 1.21–1.28 s after the last notch (six trials; the follow is already running during the notches, so the distance left at the end is smaller).
Twice the refresh rate, half the settle time
This form is "7.5% per draw", so it is set by the number of draws, not by time. From the same distance, a screen that calls requestAnimationFrame 120 times a second settles in half the time of a 60-per-second screen (by calculation; not measured on a 120 Hz device). To set it by time, scale the fraction by the time since the previous draw.
function draw(now) {
st.raf = 0; st.frames++;
const target = st.p * (COUNT - 1);
const dt = Math.min(50, now - (st.last || now)) || 16.67; st.last = now;
st.cur = still ? target : st.cur + (target - st.cur) * (1 - Math.pow(1 - 0.075, dt / 16.67));
// …painting is unchanged…
if (Math.abs(target - st.cur) > 0.02) kick(); else st.last = 0;
}
Two decisions sit in there. st.last is cleared at rest so that the first draw after the next start does not advance by the whole time spent still. Math.min(50, …) is a cap so that a long gap (a tab that went to the background, for example) does not jump the picture; in return, in a heavy scene where refreshes fall below 20 per second, the follow runs behind real time.
This version was measured six times under the same conditions. At 60 refreshes per second it settled in 1.23–1.28 s, with 0 draws in the 2 untouched seconds — nearly the same behaviour as the original.
5. Smaller decisions
-
getContext('2d', { alpha: false })tells the browser the canvas has an opaque background. Compositing may be optimised (the effect in this sample was not measured). -
Pixel density capped at 2. The canvas pixel count is display size × density. On a density-3 device, tripling it means 2.25 times the pixels of doubling. The cap is a cost limit: every extra pixel is draw time, and once the canvas has more pixels than the source image the extra ones add no detail. Density is re-read on every
size(). When only the density changes and the element size does not (moving the window to another display, for example),size()is not called; to follow that strictly, also callsize()on amatchMediaresolutionchange (not in the sample). -
ResizeObserverand100dvh. With the canvas height at100dvh, the mobile address bar showing and hiding changes the element size, andResizeObserverpicks that up.size()also recomputes progress (sync()), so a stale progress value does not survive a change in scrollable length. -
The cover calculation. Scaling by
Math.max(W / imageWidth, H / imageHeight)and centring gives the same view as CSSobject-fit: cover. On a portrait screen the sides are cut, so keep the subject in the centre of the frame. -
Reduced motion. Under
prefers-reduced-motion: reducethe follow is skipped and the frame at the scroll position is shown directly (still).
Measured values
Conditions: the sample as is / our Mac / headless Chrome 158 / three runs per viewport (six in all) / wheel of 160 px, 20 times, 110 ms apart / per-second figures are the requestAnimationFrame and drawImage counts over the 2.5 s window that contains those wheel notches, divided by 2.5.
| Item | 1440×900 | 390×844 |
|---|---|---|
requestAnimationFrame calls while scrolling |
60–61 per s | 61 per s |
drawImage while scrolling |
59–60 per s | 60 per s |
draw / drawImage in 2 untouched seconds |
0 / 0 | 0 / 0 |
| From the last wheel notch to rest | 1.21–1.26 s | 1.26–1.28 s |
| Progress after changing the viewport height | matches the calculation | matches the calculation |
| Horizontal overflow / script errors | 0 px / 0 | 0 px / 0 |
The sample's frames are simple 640×360 line drawings. With photographic frames, image decoding and size add weight, so these numbers do not carry over as they are. Nothing here was measured on a physical phone.
Summary
- Every frame of an image sequence stands alone, which is what makes going back and jumping cheap: you only pick which frame to paint
- Ask coarse-first across the whole range; stand in with the nearest frame, and swap when a closer one arrives
- Draw only while moving; once caught up, stop asking for
requestAnimationFrame - A "so many percent per draw" follow is set by the refresh count; scale by elapsed time if you want it set by time
Where we use it (245 frames; scroll to move through it): https://forma-zero.com/s/orbit-os/?utm_source=devto
Disclosure: this article was written with AI assistance (Claude). The sample code and the measured values were run and checked before publishing. The link above leads to a page of our own, where the work is also sold.
Top comments (0)