176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Light Leak — Animation Handbook</title>
<meta name="description" content="Warm light washes in from a corner at random times. Best for photo sites.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/light-leak/">
<link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
<link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
<link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="Light Leak — Animation Handbook">
<meta property="og:description" content="Warm light washes in from a corner at random times. Best for photo sites.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/light-leak/">
<meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Light Leak — Animation Handbook">
<meta name="twitter:description" content="Warm light washes in from a corner at random times. Best for photo sites.">
<meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
<script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Light Leak", "name": "Light Leak", "description": "Warm light washes in from a corner at random times. Best for photo sites.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/light-leak/", "inLanguage": "en", "articleSection": "Ambient & Background", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Ambient & Background, Light Leak"}</script>
<style>
:root{--ui-accent:#ffce5a;--leak-dur:1.2s;--leak-op:.55}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
.stage{position:relative;overflow:hidden;background:linear-gradient(135deg,#040608,#08111a)}
/* Scene content */
.scene{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:32px}
.photo-mock{width:100%;max-width:300px;height:200px;border-radius:8px;background:linear-gradient(135deg,#0d1a2e,#1a2e3a);border:1px solid rgba(255,255,255,.08);display:flex;align-items:flex-end;padding:16px}
/* Above the glow (z-index 5), so even a bright leak does not wash the caption out */
.photo-cap{position:relative;z-index:6;font-size:11px;color:rgba(255,255,255,.72)}
/* Leak overlay: the fade is a CSS transition; the gradient itself is painted by applyColor() in JS,
since the leak colour is live-editable. The dir-* class is the state flag. */
.leak{position:absolute;inset:0;pointer-events:none;z-index:5;opacity:0;transition:opacity var(--leak-dur) ease-in-out}
.leak.active{opacity:var(--leak-peak,var(--leak-op))}
/* Light spots: each floats up once and removes itself when it ends. "both" keeps a spot hidden during its start delay. */
.bokeh{position:absolute;border-radius:50%;pointer-events:none;z-index:4;animation:bokeh-float linear both;filter:blur(8px)}
@keyframes bokeh-float{from{transform:translateY(100%) scale(0);opacity:0}20%{opacity:.8}80%{opacity:.5}to{transform:translateY(-120%) scale(1.5);opacity:0}}
/* See inside and Compare: the script builds their parts once; each shows only in its mode. */
.in-only,.cmp-only,.half,.spots{display:none}
.lab{position:relative;z-index:9;padding:3px 8px;border-radius:6px;background:rgba(11,11,13,.9);color:#f4f4f2;font:600 13px/1.25 var(--hb-font);text-wrap:balance}
.stage[data-hb-mode="inside"] .in-only{display:block}
.stage[data-hb-mode="inside"] .scene,.stage[data-hb-mode="compare"] .scene{flex-direction:column;justify-content:center;gap:8px}
/* See inside: the photo, a graph of one leak under it (across: time, up: how strong) that fills the room left, and the glow's words
on the side where the light has gone. A corner at the bottom turns the column over, so the graph never sits on the glow. */
.stage[data-hb-mode="inside"] .scene{padding:10px clamp(10px,3vw,24px)}
.stage[data-hb-mode="inside"] .scene.flip{flex-direction:column-reverse}
.stage[data-hb-mode="inside"] .photo-mock{flex:none;height:clamp(60px,30%,130px)}
.stage[data-hb-mode="inside"] .photo-cap{z-index:7}
.stage[data-hb-mode="inside"] .cap-shape{max-width:62%;text-wrap:wrap}
.stage[data-hb-mode="inside"] .scene[data-side="l"] .cap-shape{align-self:flex-start}
.stage[data-hb-mode="inside"] .scene[data-side="r"] .cap-shape{align-self:flex-end}
.stage[data-hb-mode="inside"] .graph{display:grid;grid-template-rows:auto minmax(0,1fr) auto;gap:4px}
.graph{position:relative;z-index:7;flex:1 1 0;width:100%;max-width:520px;min-height:92px;max-height:170px;padding:6px 8px;border:1px solid rgba(255,255,255,.12);border-radius:10px;background:rgba(7,12,18,.88)}
.g1{justify-self:start}
.g2{justify-self:end}
.plot{position:relative;min-height:0}
.plot svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible}
.plot path{fill:none;stroke:var(--lk);stroke-width:3;stroke-linecap:round}
.plot .ax{stroke:rgba(244,244,242,.35);stroke-width:1.5}
.plot .ceil{stroke:rgba(244,244,242,.6);stroke-width:1.5;stroke-dasharray:3 4}
.plot .gap{stroke-dasharray:2 7}
.plot .dot{fill:#f4f4f2;stroke:#0b0b0d;stroke-width:2}
.lines{position:absolute;inset:0;z-index:6;width:100%;height:100%;pointer-events:none}
.lines path{fill:none;stroke:rgba(0,0,0,.55);stroke-width:5;stroke-linecap:round}
.lines .dash path{stroke:#f4f4f2;stroke-width:2;stroke-dasharray:7 6}
/* Compare: each half is half the box: its name on top, the photo, and a row of its last five leaks. The right half is the real photo
and leak; the left is a copy with its own leak layer. */
.stage[data-hb-mode="compare"]::after{content:'';position:absolute;top:0;bottom:0;left:50%;z-index:8;border-left:1px solid rgba(244,244,242,.14)}
.stage[data-hb-mode="compare"] .half{display:block;position:absolute;top:0;bottom:0;left:0;width:50%;overflow:hidden;isolation:isolate}
.stage[data-hb-mode="compare"]>.scene,.stage[data-hb-mode="compare"]>.leak{left:50%}
.stage[data-hb-mode="compare"] .scene{padding:46px 8px 8px}
.stage[data-hb-mode="compare"] .cmp-only,.stage[data-hb-mode="compare"] .spots{display:block}
.stage[data-hb-mode="compare"] .photo-mock{flex:none;height:clamp(110px,50%,150px);padding:10px}
.half-name{position:absolute;top:10px;left:50%;transform:translateX(-50%);white-space:nowrap}
.spots{position:absolute;inset:0;z-index:4;overflow:hidden;pointer-events:none}
.spots.b{left:50%}
.ticks{position:relative;flex:none;width:100%;max-width:300px;height:34px;border-bottom:1px solid rgba(244,244,242,.35)}
.tk{position:absolute;left:0;bottom:0;width:4px;height:100%;border-radius:2px 2px 0 0;background:var(--lk);transform-origin:50% 100%}
@media(max-width:600px){.lab{font-size:12px}.stage[data-hb-mode="inside"] .photo-mock{height:clamp(56px,22%,90px)}}
</style>
<link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
<script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="loop">
<nav class="hb-bar" aria-label="Animation Handbook">
<a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
<span class="hb-pager"><a href="../scanline/" rel="prev" aria-label="Previous: Scanline Effect"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Scanline Effect</span></a><a href="../starfield/" rel="next" aria-label="Next: Starfield / Space Particles"><span><span class="hb-dir">Next: </span>Starfield / Space Particles</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
<a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
<header class="hb-head">
<p class="hb-cat">07.06 · Ambient & Background</p>
<h1>Light Leak</h1>
<p class="hb-lede">Warm light washes in from a corner at random times. Best for photo sites.</p>
</header>
<section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
<div class="hb-step-head">
<span class="hb-num" aria-hidden="true">1</span>
<div><h2 id="hb-watch-title">Watch it</h2><p>Leaks come at random, a few seconds apart. Pause it to look closely, or turn on slow motion to see each leak fade.</p></div>
</div>
<div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
<button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
<button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
<button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
</div>
<div class="stage" id="stage">
<div class="scene">
<div class="photo-mock"><div class="photo-cap">ambient · atmospheric · analog warmth</div></div>
</div>
<div class="leak dir-tl" id="leak" aria-hidden="true"></div>
</div>
<div class="hb-player">
<button class="hb-play" type="button" id="btn-pause" data-hb-pause="css" data-state="playing"><svg class="hb-ic hb-i-pause" viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg><svg class="hb-ic hb-i-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3l14 9-14 9z"/></svg><span class="hb-pause-label">Pause</span></button>
<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>
</div>
<div class="hb-mode-notes" aria-live="polite">
<p data-hb-for="inside" hidden>Inside, the dashed lines show how far the glow reaches from its corner. The graph shows one leak: it fades in, holds, fades out, then stays dark for a random while.</p>
<p data-hb-for="compare" hidden>Evenly timed lights up after the same wait, at the same strength, like a machine. At random varies both, like a real film camera; the marks under each photo are its last leaks.</p>
</div>
</section>
<section class="hb-step hb-try" aria-labelledby="hb-try-title">
<div class="hb-step-head">
<span class="hb-num" aria-hidden="true">2</span>
<div><h2 id="hb-try-title">Try it</h2><p>Change a setting and see the difference as it moves.</p></div>
</div>
<div class="hb-settings">
<div class="hb-setting">
<p class="hb-setting-name" id="dir-lbl">Comes from</p>
<div class="seg" id="dir-seg" role="group" aria-labelledby="dir-lbl">
<button type="button" data-dir="dir-tl" class="on" aria-pressed="true">Top left</button>
<button type="button" data-dir="dir-tr" aria-pressed="false">Top right</button>
<button type="button" data-dir="dir-bl" aria-pressed="false">Bottom left</button>
<button type="button" data-dir="dir-br" aria-pressed="false">Bottom right</button>
<button type="button" data-dir="dir-h" aria-pressed="false">Down the middle</button>
</div>
<p class="hb-hint">Where the light spills in.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="gap-lbl">Time between leaks</p>
<div class="seg" id="gap-seg" role="group" aria-labelledby="gap-lbl">
<button type="button" data-min="0.5" data-max="1.5" aria-pressed="false">Short</button>
<button type="button" data-min="1" data-max="3" class="on" aria-pressed="true">Medium</button>
<button type="button" data-min="3" data-max="8" aria-pressed="false">Long</button>
</div>
<p class="hb-hint">Gaps are random within the range, so it never feels timed.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="speed-lbl">Speed</p>
<div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
<button type="button" data-ms="2000" aria-pressed="false">Slow</button>
<button type="button" data-ms="1200" class="on" aria-pressed="true">Normal</button>
<button type="button" data-ms="700" aria-pressed="false">Fast</button>
</div>
<p class="hb-hint">How quickly each leak fades in and out.</p>
</div>
</div>
<details class="hb-options">
<summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
<div class="hb-settings">
<div class="hb-setting">
<p class="hb-setting-name" id="bri-lbl">Brightness</p>
<div class="seg" id="bri-seg" role="group" aria-labelledby="bri-lbl">
<button type="button" data-bri="0.3" aria-pressed="false">Dim</button>
<button type="button" data-bri="0.55" class="on" aria-pressed="true">Medium</button>
<button type="button" data-bri="0.8" aria-pressed="false">Bright</button>
</div>
<p class="hb-hint">Each leak peaks a little below this, at random.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="color-lbl">Color</p>
<div class="swatches" id="color-sw" role="group" aria-labelledby="color-lbl">
<button type="button" class="on" aria-pressed="true" aria-label="Amber" data-c="#ffa532" style="background:#ffa532"></button>
<button type="button" aria-pressed="false" aria-label="Gold" data-c="#ffce5a" style="background:#ffce5a"></button>
<button type="button" aria-pressed="false" aria-label="Rose" data-c="#ff6f8b" style="background:#ff6f8b"></button>
<button type="button" aria-pressed="false" aria-label="Magenta" data-c="#ff5ca8" style="background:#ff5ca8"></button>
<button type="button" aria-pressed="false" aria-label="Cyan" data-c="#5ad1ff" style="background:#5ad1ff"></button>
</div>
<p class="hb-hint">Warm colors look like film; cyan looks cooler.</p>
</div>
<div class="hb-setting">
<label class="hb-switch-row"><span>Floating light spots</span><input class="hb-switch" type="checkbox" role="switch" id="spots-tog" autocomplete="off"></label>
<p class="hb-hint">Soft spots of light drift up after each leak.</p>
</div>
</div>
</details>
</section>
<section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
<div class="hb-step-head">
<span class="hb-num" aria-hidden="true">3</span>
<div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
</div>
<div class="hb-card">
<p class="hb-prompt">Add a light leak effect to [the photo, video or section you want it over]. Place a soft glow of light, classically warm amber, spilling in from one corner or down the middle, in a see-through layer that clicks pass through, and fade it in and out every so often, like stray light reaching the film in an old camera. Make the gaps between leaks random and vary each leak's strength a little, because evenly timed leaks look fake. Keep each leak soft, so it never looks like a flash. If the visitor has reduced motion turned on, keep the glow still and faint. Match the settings listed below.</p>
<div class="hb-chips-box" hidden>
<p class="hb-chips-title">Your settings</p>
<ul class="hb-chips"></ul>
</div>
<div class="hb-copy-row">
<button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
<p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
</div>
</div>
<div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
</section>
<section class="hb-about" aria-labelledby="hb-what-title">
<div class="hb-what">
<h2 id="hb-what-title">What it is</h2>
<div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
</div>
<div class="hb-fit">
<h2>Good for</h2>
<ul class="hb-tags hb-good"><li>Photo and film sites</li><li>Portfolios</li><li>Music pages</li><li>Lifestyle brands</li></ul>
<h3>Avoid on</h3>
<ul class="hb-tags hb-avoid"><li>Dashboards</li><li>Long reading pages</li></ul>
</div>
</section>
<section class="hb-related" aria-labelledby="hb-related-title" hidden>
<h2 id="hb-related-title">Similar animations</h2>
<div class="hb-rel-list"></div>
</section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
const stage=document.getElementById('stage');
const leak=document.getElementById('leak');
const slowTog=document.getElementById('slow-tog');
const vars=document.documentElement.style;
let minGap=1,maxGap=3,dur=1200,intensity=.55,bokehOn=false;
let curColor='rgba(255,165,50,';
// For the views: the view on show, Compare's copy of the leak layer, the leak under way (fade, brightness it was lit at, its peak) and how long its hold lasts.
let mode='normal',twinLeak=null,lit={d:dur,i:intensity,p:intensity},holdMs=0,firstHold=true;
// Pause freezes the leak under way: its fade stops where it is and the timer keeps the time it had left.
// The floating light spots are CSS keyframes, which the Pause button holds by itself; only the fade is held here.
// Every timer goes through wait(), so there is only ever one pending timer and Play can never start a second chain.
let timer=0,next=null,due=0,left=0,held=[],paused=false;
function wait(fn,ms){clearTimeout(timer);next=fn;if(paused){left=ms;return}due=performance.now()+ms;timer=setTimeout(()=>{next=null;fn()},ms)}
function freeze(){paused=true;clearTimeout(timer);if(next)left=Math.max(0,due-performance.now());held=stage.getAnimations({subtree:true}).filter(a=>a instanceof CSSTransition&&a.playState==='running');held.forEach(a=>a.pause())}
// A fade that Pause caught at or past its end is finished, not played: play() would rewind it to the start.
function thaw(){paused=false;held.forEach(a=>{if(a.playState!=='paused')return;if(a.currentTime>=a.effect.getComputedTiming().endTime)a.finish();else a.play()});held=[];if(next)wait(next,left)}
document.addEventListener('hb:pause',e=>e.detail.paused?freeze():thaw());
// The gradient is painted here because its colour is live-editable; the dir-* class says where it comes from.
const CORNER={'dir-tl':'-10% -10%','dir-tr':'110% -10%','dir-bl':'-10% 110%','dir-br':'110% 110%'};
// Where the glow's stops sit, in percent: the corner glow's four and the middle band's three (See inside draws its lines from them).
const GLOW=[0,20,50,70],BAND=[40,50,60];
const curDir=()=>[...leak.classList].find(n=>n.startsWith('dir-'));
function applyColor(){
const c=curColor,dir=curDir();
leak.style.background=dir==='dir-h'
?`linear-gradient(90deg,transparent,${c}.6) ${BAND[0]}%,${c}.8) ${BAND[1]}%,${c}.6) ${BAND[2]}%,transparent)`
:`radial-gradient(ellipse at ${CORNER[dir]},${c}.9) ${GLOW[0]}%,${c}.5) ${GLOW[1]}%,${c}.1) ${GLOW[2]}%,transparent ${GLOW[3]}%)`;
if(twinLeak)twinLeak.style.background=leak.style.background;
}
function randomGap(){return(minGap+Math.random()*(maxGap-minGap))*1000}
// Lights the glow for a leak with fade time d. Real leaks vary in strength, so each one peaks a little below the chosen brightness.
function light(d){
leak.style.setProperty('--leak-dur',d+'ms');
leak.style.setProperty('--leak-peak',(intensity*(.75+Math.random()*.25)).toFixed(3));
leak.classList.add('active');
lit={d,i:intensity,p:+leak.style.getPropertyValue('--leak-peak')};
}
// One leak: fade in, hold 200ms at the peak, fade out, then a dark gap. The next leak starts only when the glow is gone.
// Slow motion stretches this leak's fade (and the waits for it) three times; the hold and the gap keep their length.
function flash(){
const slow=slowTog.checked?3:1,d=dur*slow;
light(d);
leakStarted(d);
if(bokehOn)spawnBokeh(slow);
wait(()=>fadeOut(d),d+200);
}
// fadeD and gapTotal describe the wait under way after a fade out: the fade out itself, and its full length with the dark gap.
let fadeD=0,gapTotal=0;
function fadeOut(d){
leak.classList.remove('active');
fadeD=d;gapTotal=d+randomGap();
wait(flash,gapTotal);
if(mode==='inside')placeDot();
}
// In Compare the real leak's spots go into the right half, and a phone gives each half half the spots
function spawnBokeh(slow,host=mode==='compare'?hostB:stage){
const n=mode==='compare'&&matchMedia('(max-width:600px),(max-height:500px)').matches?1:3;
for(let i=0;i<n;i++){
const b=document.createElement('div');b.className='bokeh';
const sz=20+Math.random()*40;
b.style.cssText=`width:${sz}px;height:${sz}px;background:${curColor}.6);left:${20+Math.random()*60}%;bottom:0;animation-duration:${(3+Math.random()*4)*slow}s;animation-delay:${Math.random()*.5}s`;
b.addEventListener('animationend',()=>b.remove());
host.appendChild(b);
}
}
function choices(id,pick){
const buttons=document.querySelectorAll('#'+id+' button');
buttons.forEach(b=>b.addEventListener('click',()=>{
buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
pick(b.dataset);
}));
}
// Comes from and Color repaint the glow at once, even while paused. Time between leaks plans the wait under way again (below).
// Speed, Brightness and Floating light spots are read by the next leak; Brightness never writes --leak-peak here,
// because that would restart a fade that Pause is holding.
choices('dir-seg',d=>{
leak.classList.remove('dir-tl','dir-tr','dir-bl','dir-br','dir-h');
leak.classList.add(d.dir);
applyColor();
});
// A leak under way keeps its timing and uses the new range for the gap after it. A fade out or dark gap under way is planned
// again from the new range: it counts the time already waited and never ends before the fade out does.
choices('gap-seg',d=>{
const lo=+d.min,hi=+d.max;
if(lo===minGap&&hi===maxGap)return;
minGap=lo;maxGap=hi;
if(next!==flash)return;
const waited=gapTotal-(paused?left:Math.max(0,due-performance.now()));
gapTotal=fadeD+randomGap();
wait(flash,Math.max(0,gapTotal-waited));
});
choices('speed-seg',d=>{dur=+d.ms});
choices('bri-seg',d=>{intensity=+d.bri;vars.setProperty('--leak-op',intensity)});
choices('color-sw',d=>{
const h=d.c;
curColor=`rgba(${parseInt(h.slice(1,3),16)},${parseInt(h.slice(3,5),16)},${parseInt(h.slice(5,7),16)},`;
applyColor();
});
document.getElementById('spots-tog').addEventListener('change',e=>{bokehOn=e.target.checked});
applyColor();
// The first picture is a leak at its peak, with no fade in, so a stage that is paused on arrival (reduced motion) already
// shows the effect. It holds for one gap, then fades out and the chain carries on as usual.
const firstFade=dur;
light(firstFade);
leak.getAnimations().forEach(a=>a.finish());
holdMs=randomGap();
wait(()=>{firstHold=false;fadeOut(firstFade)},holdMs);
// ── See inside and Compare: built once, shown only in their mode; Normal never touches them. They draw from the page's own numbers:
// the glow's stops, the fade, the gap range, the brightness, and the timer chain's next, due and left.
const motionOk=!matchMedia('(prefers-reduced-motion:reduce)').matches;
const TOP=.85,EVEN=.875,CORNERS={'dir-tl':'top left','dir-tr':'top right','dir-bl':'bottom left','dir-br':'bottom right'};
const scene=stage.querySelector('.scene'),leakCS=getComputedStyle(leak),txt=(e,s)=>{if(e.textContent!==s)e.textContent=s};
const cap=(cls,s='')=>`<span class="lab ${cls}" data-hb-caption aria-hidden="true">${s}</span>`;
// Compare: a name and a row of five ticks in each half. The left half is a copy of the scene (inert, no ids) with its own leak layer.
scene.insertAdjacentHTML('beforeend',cap('half-name cmp-only','At random')+'<div class="ticks cmp-only" aria-hidden="true">'+'<i class="tk"></i>'.repeat(5)+'</div>');
const sceneA=scene.cloneNode(true);
stage.insertAdjacentHTML('beforeend','<div class="half" aria-hidden="true"><div class="leak"></div><div class="spots"></div></div><div class="spots b"></div>');
const half=stage.querySelector('.half'),hostA=half.querySelector('.spots'),hostB=stage.querySelector('.spots.b');
twinLeak=half.querySelector('.leak');half.inert=true;half.prepend(sceneA);
txt(sceneA.querySelector('.half-name'),'Evenly timed');
const ticksB=scene.querySelector('.ticks'),rowA=[...sceneA.querySelectorAll('.tk')],rowB=[...ticksB.children];
// See inside: the graph, the glow's words and the dashed lines over the whole box
scene.insertAdjacentHTML('beforeend','<div class="graph in-only" aria-hidden="true">'+cap('g1')+'<div class="plot"><svg><path class="ax"/><path class="ceil"/><path class="gap"/><path class="curve"/><circle class="dot" r="5"/></svg></div>'+cap('g2')+'</div>'+cap('cap-shape in-only'));
stage.insertAdjacentHTML('beforeend','<svg class="lines in-only" aria-hidden="true"><g><path/><path/></g><g class="dash"><path/><path/></g></svg>');
const [g1,g2]=scene.querySelectorAll('.g1,.g2'),capShape=scene.querySelector('.cap-shape'),plot=scene.querySelector('.plot'),svg=plot.firstChild;
const [ax,ceil,gap,curve]=svg.children,dot=svg.lastChild,lines=stage.lastElementChild,linePaths=lines.querySelectorAll('path');
// The dashed lines: ellipses round the corner at the 20% and 70% stops (farthest-corner: the farthest sides' ellipse times the square root of 2), or the band's 40% and 60%.
function drawLines(){
const W=stage.clientWidth,H=stage.clientHeight,dir=curDir();
let d=[BAND[0],BAND[2]].map(p=>`M${W*p/100} 0V${H}`);
if(dir!=='dir-h'){
const [px,py]=CORNER[dir].split(' ').map(parseFloat),cx=W*px/100,cy=H*py/100;
const rx=Math.SQRT2*Math.max(cx,W-cx),ry=Math.SQRT2*Math.max(cy,H-cy);
d=[GLOW[1],GLOW[3]].map(s=>{const a=rx*s/100,b=ry*s/100;return`M${cx-a} ${cy}A${a} ${b} 0 1 0 ${cx+a} ${cy}A${a} ${b} 0 1 0 ${cx-a} ${cy}`});
}
lines.setAttribute('viewBox',`0 0 ${W} ${H}`);
linePaths.forEach((p,i)=>p.setAttribute('d',d[i%2]));
}
// The graph is the plan for one leak at the settings now: the fade in and out (three times as long in slow motion), the 200 ms hold,
// then the dark gap, solid for its shortest and dashed up to its longest. Its peak is this leak's own strength at the brightness now.
let G=null;
function drawGraph(){
const W=plot.clientWidth,H=plot.clientHeight;if(!W||!H)return;
const d=dur*(slowTog.checked?3:1),pk=lit.p/lit.i*intensity,T=2*d+200+maxGap*1000;
const x=t=>6+(W-12)*t/T,y=v=>H-6-(H-12)*Math.min(v/TOP,1),b=y(0),p=y(pk),m=x(2*d+200+minGap*1000);
svg.setAttribute('viewBox',`0 0 ${W} ${H}`);
ax.setAttribute('d',`M${x(0)} ${b}H${x(T)}`);
ceil.setAttribute('d',`M${x(0)} ${y(intensity)}H${x(T)}`);
curve.setAttribute('d',`M${x(0)} ${b}C${x(d*.42)} ${b} ${x(d*.58)} ${p} ${x(d)} ${p}H${x(d+200)}C${x(d*1.42+200)} ${p} ${x(d*1.58+200)} ${b} ${x(2*d+200)} ${b}H${m}`);
gap.setAttribute('d',`M${m} ${b}H${x(T)}`);
txt(g1,'One leak: fades in, holds, fades out'+(bokehOn?', then light spots float up':''));
txt(g2,`then dark for a random ${minGap} to ${maxGap} seconds`);
G={x,y,d,pk,T};
}
// The dot: across with the time since this leak began (the wait under way, less what is left of it, so it stops when the chain is held),
// up with the leak layer's real opacity. The first leak waits at the top. Under reduced motion a playing chain puts it at the end of the part under way.
function placeDot(){
if(!G||mode!=='inside')return;
const gapPart=next===flash,rem=paused?left:Math.max(0,due-performance.now()),e=(gapPart?gapTotal:holdMs)-rem,k=G.d/lit.d,end=!motionOk&&!paused;
let t=G.d+100,o=end?(gapPart?0:1):Math.min(parseFloat(leakCS.opacity)/lit.p,1);
if(gapPart)t=end?2*G.d+200:e<lit.d?G.d+200+e*k:2*G.d+200+e-lit.d;
else if(!firstHold&&!end)t=e<lit.d?e*k:G.d+Math.min(e-lit.d,200);
dot.style.transform=`translate(${G.x(Math.min(t,G.T))}px,${G.y(o*G.pk)}px)`;
}
let raf=0;
function ride(){
cancelAnimationFrame(raf);raf=0;
if(mode!=='inside'||paused||!motionOk)return;
const step=()=>{placeDot();raf=requestAnimationFrame(step)};step();
}
// The ticks: a row of the last five leaks, each as tall as its peak and spaced by the time between them. Evenly timed has five equal
// ones; At random starts from a fixed plan and takes each real leak as it starts (the time since the one before, how strong).
const rnd=[{f:.5,r:.98},{f:.95,r:.77},{f:.1,r:.92},{f:.75,r:.75},{f:0,r:.95}];
function leakStarted(d){
rnd.push({iv:holdMs+gapTotal,r:lit.p/lit.i});rnd.shift();
holdMs=d+200;
if(mode==='inside'){drawGraph();placeDot()}
if(mode==='compare')placeTicks();
}
function placeTicks(){
const W=ticksB.clientWidth;if(!W)return;
const base=2*dur*(slowTog.checked?3:1)+200,iv=l=>l.iv??base+(minGap+l.f*(maxGap-minGap))*1000;
// Leaks timed at an earlier, longer setting widen the scale, so all five ticks stay in the row
const s=.9*(W-8)/Math.max(4*(base+maxGap*1000),rnd.slice(1).reduce((a,l)=>a+iv(l),0));
const put=(row,list)=>{
let x=W-6;
for(let i=4;i>=0;i--){
row[i].style.transform=`translateX(${Math.max(x-2,0)}px) scaleY(${Math.min(list[i].r*intensity/TOP,1)})`;
x-=iv(list[i])*s;
}
};
put(rowA,Array(5).fill({iv:base+(minGap+maxGap)*500,r:EVEN}));put(rowB,rnd);
}
// Evenly timed: its own small chain (wait() keeps only one timer), every leak after the same wait and at the same strength, held and
// resumed with the page's. Pause already holds its fade, a transition in the stage.
let eTimer=0,eNext=null,eDue=0,eLeft=0,eTotal=0,eFade=0,eBeat=0;
const beat=()=>(minGap+maxGap)*500;
function eWait(fn,ms){clearTimeout(eTimer);eNext=fn;if(paused){eLeft=ms;return}eDue=performance.now()+ms;eTimer=setTimeout(()=>{eNext=null;fn()},ms)}
function eFlash(){
const s=slowTog.checked?3:1,d=dur*s;
if(twinLeak.style.opacity){twinLeak.style.transition='';void twinLeak.offsetWidth;twinLeak.style.opacity=''}
twinLeak.style.setProperty('--leak-dur',d+'ms');
twinLeak.style.setProperty('--leak-peak',(intensity*EVEN).toFixed(3));
twinLeak.classList.add('active');
if(bokehOn)spawnBokeh(s,hostA);
eWait(()=>{twinLeak.classList.remove('active');eFade=d;eBeat=beat();eTotal=d+eBeat;eWait(eFlash,eTotal)},d+200);
}
// Time between leaks: a dark wait under way is planned again from the new beat, as the page does for its own
function eReplan(){
if(eNext!==eFlash||beat()===eBeat)return;
const waited=eTotal-(paused?eLeft:Math.max(0,eDue-performance.now()));
eBeat=beat();eTotal=eFade+eBeat;eWait(eFlash,Math.max(0,eTotal-waited));
}
// Entering: the copy starts lit from dark with a fade in, or, held, shows the real leak's light as it is. Leaving: its chain stops.
function enterCompare(){
stage.querySelectorAll(':scope>.bokeh').forEach(b=>b.remove());
void half.offsetWidth;
if(paused){twinLeak.style.transition='none';twinLeak.style.opacity=leakCS.opacity}
else eFlash();
}
function leaveCompare(){
clearTimeout(eTimer);eNext=null;
twinLeak.classList.remove('active');twinLeak.style.opacity=twinLeak.style.transition='';
hostA.textContent=hostB.textContent='';
}
// Notes: the markup holds the corner's words for moving; a band, and a loop held under reduced motion, get their own
const notes={inside:document.querySelector('[data-hb-for="inside"]'),compare:document.querySelector('[data-hb-for="compare"]')};
const words={inside:notes.inside.textContent,compare:notes.compare.textContent};
function setNotes(){
const still=!motionOk&&paused,band=curDir()==='dir-h';
txt(notes.inside,still
?`Inside, shown still: the dashed lines show ${band?'where the glow is brightest':'how far the glow reaches'}, and the graph shows one leak fading in, holding and fading out, then a random dark wait.`
:band?words.inside.replace('how far the glow reaches from its corner','where the glow is brightest, down the middle'):words.inside);
txt(notes.compare,still?'Shown still: the marks under each photo are its last five leaks, equal and evenly spaced in Evenly timed, uneven in At random.':words.compare);
}
function refresh(){
vars.setProperty('--lk',curColor+'1)');
const dir=curDir();
if(mode==='inside'){
scene.classList.toggle('flip',dir[4]==='b');scene.dataset.side=dir==='dir-h'?'c':dir[5]==='l'?'r':'l';
txt(capShape,dir==='dir-h'?'Brightest down the middle':`Light from the ${CORNERS[dir]} corner, gone by the outer line`);
drawLines();drawGraph();placeDot();
}
if(mode==='compare'){eReplan();placeTicks()}
setNotes();
}
document.addEventListener('hb:mode',e=>{
const was=mode;mode=e.detail.mode;
if(was==='compare'&&mode!=='compare')leaveCompare();
if(mode==='compare'&&was!=='compare')enterCompare();
refresh();ride();
});
document.addEventListener('hb:pause',e=>{
if(e.detail.paused){clearTimeout(eTimer);if(eNext)eLeft=Math.max(0,eDue-performance.now())}
else if(mode==='compare'){if(eNext)eWait(eNext,eLeft);else eFlash()}
placeDot();ride();setNotes();
});
document.addEventListener('click',e=>{if(e.target.closest('#dir-seg,#gap-seg,#speed-seg,#bri-seg,#color-sw'))refresh()});
document.addEventListener('change',e=>{if(e.target.matches('#spots-tog,#slow-tog'))refresh()});
new ResizeObserver(()=>{if(mode!=='normal')refresh()}).observe(stage);
new ResizeObserver(()=>{if(mode==='inside'){drawGraph();placeDot()}}).observe(plot);
applyColor();
</script>
</body>
</html>