Pixel diff visual regression for a refactor
I moved a live game's controls onto a new UI kit and had to prove nothing looked different. A pixel diff was useless until I ran it against itself first.
Contents
I had a refactor that was supposed to change nothing anyone could see. ASMR Logo Craft Block draws its own buttons, popups, settings switches and stats tabs, and each had grown its own copy of the press-and-squish behaviour. I was moving all of them onto an unstyled UI kit I share between my games: the kit brings the behaviour and the accessibility, the game keeps every pixel of its look.
"Should look the same" is not something I accept from myself any more. The rule I work to for visual and performance refactors is that the result is pixel-identical, with a small allowance for anti-aliasing at edges, and that I prove it with screenshots rather than by squinting. This post is how that proof was built, and mostly how wrong it was before I gave it a control.
The setup: two builds, three captures
The visual regression test is a Node script around two libraries: Playwright's WebKit build
(playwright-core) to drive the game, and sharp to read the PNGs. WebKit rather than
Chromium because it is the engine the iOS build runs in.
It serves two web builds of the game side by side:
- before: the last commit, built from a clean worktree;
- after: the working tree with the refactor in it.
For each screen state it captures three times: before, before again, and after. The first two are compared with each other to make the control. The first and third make the change. A state passes when the change has no more visible pixels than the control does, and when every palette colour variable on the page root reads the same in both builds.
Everything that could differ between runs gets pinned. The viewport is 390×844 at 2× scale, so
each screenshot is 780×1688, or 1,316,640 pixels. The clock is frozen with Playwright's
context.clock.setFixedTime. Math.random is replaced by a seeded generator before any page
script runs. The game's QA build has a test bridge that can load a save, open a route and
report when the board is idle, so each of the 34 states is reached the same way every time:
home, settings, a switch mid-press, the shop, a win, the offline screen and the rest.
"Visible" needed a number. A pixel counts as different if any channel moved at all, and as visibly different if a channel moved by more than 24 of 255. Below that it is the faint fringe you get when an edge lands a fraction of a pixel elsewhere.
Freezing the frame
A screenshot of a game is a screenshot of something moving. The background drifts on a 28-second loop, sparkles twinkle on loops between 2.6 and 4.7 seconds, and home's tagline slides in over 300 ms. Two shots of the same build taken a moment apart will never match unless every animation is stopped at a point both runs agree on.
The Web Animations API makes that possible, because document.getAnimations() returns the
CSS animations and transitions too, not only the ones script started. A simplified version of
what my harness runs just before each shot:
// Simplified: stop every animation at a point two runs agree on.
await page.evaluate((atMs) => {
const pressAt = window.__pressAt ?? Infinity; // set by the harness when it taps
for (const anim of document.getAnimations()) {
const timing = anim.effect?.getComputedTiming();
if (atMs != null && anim.startTime >= pressAt) anim.currentTime = atMs; // what the tap started
else if (timing?.iterations === Infinity) anim.currentTime = 0; // loops: at their start
else anim.finish(); // the rest: at their end
anim.pause();
}
}, state.at);
at is how far into a press the frame is taken: 80 ms for a button mid-squish, 110 ms into a
popup closing. States without one are taken at rest. Then page.screenshot is called with
animations: 'allow', so Playwright leaves every animation where the freeze put it.
Running it against itself first
Before comparing the refactor with anything, I ran the harness with the old build on both sides. Every state should pass with almost nothing in either number. A few lines from that first run:
✗ settings-press-tile: 1316636 px differ (897689 visibly); control 76 (0)
✗ settings-sound-off: 1063875 px differ (386889 visibly); control 99 (0)
✗ settings-advanced: 1140055 px differ (296661 visibly); control 1140055 (296660)
✗ backdrop-sunset: 1060014 px differ (393572 visibly); control 6970 (0)
Same code on both sides, and 1,316,636 of 1,316,640 pixels different. Had I gone straight to before-versus-after, every one of those would have read as a regression from the refactor.
The machine was not helping. Other work was running on it, including several emulators and simulators, with a load average between 47 and 78 during that first pass. Nothing there was mine to stop, so the harness had to get steady under load rather than on a quiet machine. The emulator side of that problem is in how I made the Android emulator faster; this was the browser side.
What kept moving
It took five self-test runs to get most states steady. Each fix came from opening the diff image of a state that failed against itself and asking what had moved.
- Freezing once was not enough. Layout could still settle after the freeze, and a little motion is driven from script rather than CSS. The harness now freezes, shoots, and repeats until two shots in a row are byte-identical, up to 15 tries.
- The test bridge's "idle" only knew the game's own motion. The board and the flying coins report when they are done. A popup springing in is plain CSS and reports nothing. The harness now also waits until no animation that has an end is still running.
- The splash replayed. Loading a save reloads the page, and the splash plays once per launch, so states were being shot mid-splash. Home's first self-test after the earlier fixes differed in 1,078,211 pixels against a control of 0. The harness now waits for the splash to be gone, then 1.8 seconds for the popup home may offer.
- A state's three captures ran in parallel. They run one after another now, to take some load off a busy machine.
- Taps raced popups. The backdrop states chose a background in settings, closed the popup and reopened settings. Sometimes the reopen did not take, in either build: two "before" shots would end on plain home while "after" showed settings, or the other way round. I stopped tapping my way there. The backdrop is written to storage the way the game stores it, the page is reloaded, and no tap is involved.
Two smaller changes made the rest readable. The change is now measured against whichever of the two "before" shots is closer, because noise that comes and goes in "before" comes and goes in "after" too. And each capture gets a three-minute limit, after one page that never settled hung an entire run.
The last noise source was the most useful lesson. One count kept turning up: 439 visibly different pixels, with about 156,320 faint ones. It appeared in a before-versus-before control, then again on the real comparison for settings and for two presses inside settings. When I cropped the diff, all 439 were in the dimmed home screen behind the popup: the edges of the logo, the level medallions and the floating buttons. Home's own motion had been paused at whatever moment the popup covered it. The popup itself matched exactly. A difference that repeats to the pixel across unrelated runs is a fingerprint, and once I knew this one I could recognise it rather than re-investigate it.
The one real change
With the control in place, the comparison of the old game against the refactor mostly came back with single-digit counts or none at all: home 3 pixels, settings 1, a jelly button mid-press 0, the shop 0, the game board 0. Then the daily-rewards popup failed, and that one was real.
That popup opens by itself at launch, before the player has touched anything. The kit's popup
moved focus to its first control when it opened, which was the Claim button. WebKit treated
that focus as :focus-visible, so Claim drew a focus ring the old game had never shown. A
player would have seen it too, since the gift popup can open before the first tap.
The harness logged focus alongside every shot, which is what made this quick to read. When
settings was opened by a tap, focus landed on its first tile with :focus-visible false and no
ring. When the rewards popup opened itself, focus landed on Claim with :focus-visible true.
Same component; what differed between the two was whether anything had been tapped first.
The fix went in the kit, which owns focus:
- The dialog focuses itself on open, not its first control. It already had
tabIndex=-1, and this is an accepted pattern for dialogs: a screen reader announces the dialog, and Tab goes to the first control. - Shift+Tab from the dialog wraps to its last control, so focus stays trapped both ways.
- The ring is hidden on the dialog box only. A control reached by keyboard still shows its own.
Moving focus into a dialog when it opens has caught me before, in a lightbox where focus()
quietly did nothing. Focus is the one part of a "purely
visual" refactor that screenshots catch only if a ring happens to draw.
The fix had a side effect the harness caught too. With focus on the popup itself, settings went from 1 differing pixel to 35,337. None were visible. I measured the actual gaps: about 33,500 pixels were 1 level apart, about 1,800 were 2, and 16 were 3 of 255. All of them sat on the glossy gradients, the tile bubbles and the round jellies. My guess is that WebKit rasterises those gradients on a different layer once the popup holds focus, but I did not prove that. No eye sees 3 levels. It is still not pixel-identical, so it went in my notes as "faint gradient tint, at most 3/255" and not as "identical". The sound-off state showed the same tint in one run and came back at 0 in the next, so it comes and goes.
What it proved, and what it didn't
The first full comparison, 3 captures × 34 states one after another, ran past 30 minutes. That was too slow, so the remaining states ran 4 at a time, with each state's own three captures still in order so the control stays fair.
Where it landed:
- Nothing visible changed except anti-aliasing: a coin rim and a puzzle piece on the win screen at 1,375 visible pixels, a count that had also turned up in a before-versus-before run, and the gradient tint above.
- 8,052 unit tests passed, and the device scenarios passed on both platforms: 11 of 11 on an Android emulator and 9 of 9 on the iOS simulator.
- One state was never compared. The harness could not tap the restart button on the game screen, and it could not on the old build either, so that confirmation popup is unproven.
- The backdrop states are the weakest part. In the final run, three of the four plain backdrops still differed by about 25,000 visible pixels against smaller controls. That is close to the home-behind-a-popup noise I had measured between two old builds (23,462 and 23,999), and I counted them as that noise. One backdrop with settings open came in at 1,196 visible pixels against a control of 1,026. I did not open those four diffs one by one, so calling them noise is a reasonable reading, not a proof.
When the branch later had to be rebased onto other work, I reran the eight settings and press states against a fresh build of the new base. All eight passed.
What I'd keep
- Run the diff against itself before trusting it. The control is how much a run varies when nothing changed, and that is the bar the real change has to clear.
- Freeze with
getAnimations(), then shoot until two shots match. - Seed the state; don't tap your way to it. Every tap I removed took a race with it.
- Log focus and
:focus-visiblenext to each screenshot. The only real regression was a focus ring, and the log said why before I opened the image.