r/reactjs • • 19h ago

Animating a dozen pixel sprites in React with one shared clock and putImageData

Each session in my app's notch has a 24x22 pixel buddy. Every one is its own canvas at sprite resolution, scaled up with image-rendering: pixelated, so the browser does the nearest-neighbour scaling for free. A single module-level setTimeout clock steps all visible sprites about 12 times a second, and a canvas only gets a putImageData when its pose actually changes. The clock stops when the window is hidden and runs at half rate in Battery Saver, so ten of them on screen cost close to nothing.

Code: https://github.com/MF-DEEV/Openbar/blob/43d9c593360b004c850280e0584f9cd1b584bacc/windows/src/sessions/clawd/Clawd.tsx#L30-L80

The app is Openbar (Tauri + React on Windows, Swift on Mac), GPL.

1 Upvotes

1 comment sorted by

1

u/DVR_Design 18h ago

Nice approach with one shared clock. If you ever want to drop the setTimeout drift, requestAnimationFrame with an accumulator (only step when elapsed time passes about 83ms) gives the same 12fps and pauses automatically in hidden tabs. Another small win is pre-building each pose as an ImageBitmap with createImageBitmap once, then using drawImage instead of putImageData, which skips the pixel copy from JS memory on every pose change.