Three canvases, one shader source, zero wasted frames. Each instance pauses automatically when off-screen—scroll to watch them toggle in the stats panel.
The browser's IntersectionObserver fires when an element crosses the viewport threshold.
No scroll listeners, no getBoundingClientRect() polling—just a callback when visibility changes.
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
state.visible = entry.isIntersecting;
});
}, {
threshold: 0.01, // 1% visible triggers
rootMargin: '50px' // pre-warm before entering view
});
Why it matters: Scroll events fire continuously; observers fire once per state change.
The render loop calls onBeforeFrame every frame. If your visibility flag is false,
return early—the library skips the draw call entirely.
onBeforeFrame: function(ctx) {
if (!state.visible) return; // no GPU work
state.frameCount++;
}
Bonus: Pause uniforms too—skip updating iTime so the animation
freezes exactly where it left off when the canvas re-enters view.
One <script type="x-shader/x-fragment"> serves all three canvases. Each instance
passes a different iPhase uniform to offset the color cycle.
const phaseOffsets = {
1: 0,
2: Math.PI * 2 / 3, // 120°
3: Math.PI * 4 / 3 // 240°
};
// In uniforms
iPhase: (gl, loc) => gl.uniform1f(loc, phaseOffsets[canvasId])
Result: Visual variety with zero code duplication.
When the user switches tabs, document.hidden becomes true. Pause all shaders
to avoid burning CPU/GPU in the background.
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
state.visible = false;
}
});
Takeaway: Combine IntersectionObserver + visibilitychange
for bulletproof idle detection.