Skip to content

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.

27.6 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grain / Film Noise Overlay — Animation Handbook</title>
  <meta name="description" content="Fine grain flickers over the page, like old film. Best for editorial sites.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/grain-overlay/">
  <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="Grain / Film Noise Overlay — Animation Handbook">
  <meta property="og:description" content="Fine grain flickers over the page, like old film. Best for editorial sites.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/grain-overlay/">
  <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="Grain / Film Noise Overlay — Animation Handbook">
  <meta name="twitter:description" content="Fine grain flickers over the page, like old film. Best for editorial 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": "Grain / Film Noise Overlay", "name": "Grain / Film Noise Overlay", "description": "Fine grain flickers over the page, like old film. Best for editorial sites.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/grain-overlay/", "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, Grain / Film Noise Overlay"}</script>
  <style>
    :root{--ui-accent:#ffce5a;--grain-op:0.08;--grain-blend:overlay;--pill:rgba(5,6,10,.92);--pill-ink:#f4f4f2;--pill-sub:#c4c8d2;--zoom:4}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;overflow:hidden}
    /* Scene beneath grain */
    .scene{position:absolute;inset:0;background:linear-gradient(135deg,#0a1520,#152035,#0a2520);display:flex;align-items:center;justify-content:center;padding:24px}
    .hero-mock{text-align:center;max-width:360px}
    .hero-label{font-size:11px;letter-spacing:3px;text-transform:uppercase;color:rgba(88,166,255,.85);margin-bottom:12px}
    .hero-h{font-size:clamp(22px,3.5vw,36px);font-weight:700;color:#fff;line-height:1.2;margin-bottom:12px}
    .hero-p{font-size:13px;color:rgba(255,255,255,.72);line-height:1.7;max-width:280px;margin:0 auto}
    /* SVG grain filter approach: a zero-size SVG rather than display:none, from which some browsers draw no filter */
    .grain-svg{position:absolute;width:0;height:0}
    /* Canvas grain overlay */
    .grain-canvas{position:absolute;inset:0;pointer-events:none;z-index:5;opacity:var(--grain-op);mix-blend-mode:var(--grain-blend)}
    canvas{display:block;width:100%;height:100%}
    /* SVG filter grain */
    .grain-filter-wrap{position:absolute;inset:0;pointer-events:none;z-index:5;opacity:var(--grain-op);mix-blend-mode:var(--grain-blend);display:none}
    .grain-filter-wrap rect{width:100%;height:100%;filter:url(#grain-filter)}
    /* The scene and its grain sit in .world inside .win; in Normal both are plain wrappers that fill the stage */
    .win,.world{position:absolute;inset:0}
    /* See inside and Compare: a band of plain grain, a copy of the scene, a divider and plain words over the picture */
    .half,.band,.divider,.lbl{display:none;position:absolute}
    .half{top:0;bottom:0;left:0;width:50%;overflow:hidden}
    .band{left:0;right:0;top:0;overflow:hidden;border-bottom:2px dashed var(--pill-ink);z-index:6}
    .band canvas,.band .bsvg{position:absolute;left:0;top:0}
    .band .bsvg{display:none;width:100%}
    .divider{top:0;bottom:0;left:50%;width:2px;margin-left:-1px;background:#2a2b33;z-index:7}
    .lbl{z-index:8;padding:4px 9px;border-radius:14px;background:var(--pill);color:var(--pill-ink);font:600 13px/1.25 var(--hb-font)}
    .lbl small{display:block;font:500 12px/1.25 var(--hb-font);color:var(--pill-sub)}
    .ib,.ia{left:10px;max-width:calc(100% - 20px)}
    .ib{top:10px;max-width:calc(72% - 10px)}
    .ia{bottom:10px}
    .hn{top:8px;max-width:calc(50% - 14px);white-space:nowrap}
    .hn small{white-space:normal}
    .hn.a{left:8px}
    .hn.b{left:calc(50% + 8px)}
    .stage[data-hb-mode="inside"] .band,.stage[data-hb-mode="inside"] .ib,.stage[data-hb-mode="inside"] .ia,
    .stage[data-hb-mode="compare"] .half,.stage[data-hb-mode="compare"] .divider,.stage[data-hb-mode="compare"] .hn{display:block}
    .stage[data-hb-mode="inside"] .band.svg canvas{display:none}
    .stage[data-hb-mode="inside"] .band.svg .bsvg{display:block}
    /* Compare: each half is a window onto the same spot of the scene, magnified; the second window holds the real scene and grain */
    .stage[data-hb-mode="compare"] .win{left:50%;overflow:hidden}
    .stage[data-hb-mode="compare"] .world{inset:auto;left:0;top:0;width:var(--sw);height:var(--sh);transform-origin:0 0;transform:translate(var(--tx),var(--ty)) scale(var(--zoom))}
    .stage[data-hb-mode="compare"] #grain-cvs{image-rendering:pixelated}
    /* both windows get the same lift, so the faint grain can be seen; the half names say so */
    .stage[data-hb-mode="compare"] .half,.stage[data-hb-mode="compare"] .win{filter:brightness(2.2) contrast(1.3) saturate(2)}
  </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="../aurora/" rel="prev" aria-label="Previous: Aurora / Northern Lights"><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>Aurora / Northern Lights</span></a><a href="../scanline/" rel="next" aria-label="Next: Scanline Effect"><span><span class="hb-dir">Next: </span>Scanline Effect</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.04 · Ambient &amp; Background</p>
    <h1>Grain / Film Noise Overlay</h1>
    <p class="hb-lede">Fine grain flickers over the page, like old film. Best for editorial 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>It moves by itself. Pause it to look closely, or turn on slow motion to see each part of the movement.</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">
      <div class="half" aria-hidden="true" inert><div class="world" id="world-a"></div></div>
      <div class="win"><div class="world" id="world">
        <div class="scene">
          <div class="hero-mock">
            <div class="hero-label">Atlas Studio</div>
            <div class="hero-h">Design without compromise</div>
            <div class="hero-p">We craft digital products that earn attention and keep it. Every pixel, every frame, considered.</div>
          </div>
        </div>
        <!-- SVG filter grain -->
        <svg class="grain-svg" aria-hidden="true"><defs><filter id="grain-filter" x="0%" y="0%" width="100%" height="100%" color-interpolation-filters="sRGB"><feTurbulence type="fractalNoise" baseFrequency="0.65" numOctaves="3" stitchTiles="stitch" id="grain-turb"/><feColorMatrix type="saturate" values="0"/><feComponentTransfer><feFuncR type="linear" slope="3" intercept="-1"/><feFuncG type="linear" slope="3" intercept="-1"/><feFuncB type="linear" slope="3" intercept="-1"/><feFuncA type="linear" slope="0" intercept="1"/></feComponentTransfer></filter></defs></svg>
        <div class="grain-filter-wrap" id="grain-filter-wrap" aria-hidden="true"><svg width="100%" height="100%"><rect width="100%" height="100%" filter="url(#grain-filter)"/></svg></div>
        <!-- Canvas grain -->
        <div class="grain-canvas" id="grain-canvas-wrap" aria-hidden="true"><canvas id="grain-cvs"></canvas></div>
      </div></div>
      <div class="band" id="band" aria-hidden="true"><canvas id="band-cvs"></canvas><svg class="bsvg" aria-hidden="true"><rect width="100%" height="100%" filter="url(#grain-filter)"/></svg></div>
      <div class="divider" aria-hidden="true"></div>
      <p class="lbl ib" id="cap-band" aria-hidden="true" data-hb-caption>The grain on its own: random dots, new ones 24 times a second</p>
      <p class="lbl ia" id="cap-laid" aria-hidden="true" data-hb-caption>Laid over the page at a twelfth of that strength, adding contrast</p>
      <p class="lbl hn a" aria-hidden="true" data-hb-caption>Without grain<small>Zoomed in and brightened</small></p>
      <p class="lbl hn b" aria-hidden="true" data-hb-caption>With grain<small>Zoomed in and brightened</small></p>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-pause" data-hb-pause 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 top band shows the grain on its own at full strength: random dots that keep changing. Below, the same grain is laid over the page so faintly you barely see it.</p>
      <p data-hb-for="compare" hidden>Both halves are zoomed in and brightened on the same spot: Without grain is smooth, while With grain adds faint flickering dots, felt more than seen. Pick Strong in Try it to see them plainly.</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="str-lbl">Strength</p>
        <div class="seg" id="str-seg" role="group" aria-labelledby="str-lbl">
          <button type="button" data-op="0.04" aria-pressed="false">Faint</button>
          <button type="button" data-op="0.08" class="on" aria-pressed="true">Light</button>
          <button type="button" data-op="0.16" aria-pressed="false">Strong</button>
        </div>
        <p class="hb-hint">Grain works best when it is felt more than seen.</p>
      </div>
      <div class="hb-setting" id="size-setting">
        <p class="hb-setting-name" id="size-lbl">Grain size</p>
        <div class="seg" id="size-seg" role="group" aria-labelledby="size-lbl">
          <button type="button" data-px="1" aria-pressed="false">Fine</button>
          <button type="button" data-px="2" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-px="3" aria-pressed="false">Coarse</button>
        </div>
        <p class="hb-hint">Coarse grain looks like old film stock.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="rate-lbl">How often it changes</p>
        <div class="seg" id="rate-seg" role="group" aria-labelledby="rate-lbl">
          <button type="button" data-fps="60" aria-pressed="false">Every frame</button>
          <button type="button" data-fps="24" class="on" aria-pressed="true">Like film</button>
          <button type="button" data-fps="12" aria-pressed="false">Choppy</button>
          <button type="button" data-fps="4" aria-pressed="false">Slow</button>
        </div>
        <p class="hb-hint">Film grain changes 24 times a second; phones cap it there.</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="blend-lbl">Blend</p>
          <div class="seg" id="blend-seg" role="group" aria-labelledby="blend-lbl">
            <button type="button" data-blend="overlay" class="on" aria-pressed="true">Film</button>
            <button type="button" data-blend="screen" aria-pressed="false">Lighter</button>
            <button type="button" data-blend="soft-light" aria-pressed="false">Softer</button>
          </div>
          <p class="hb-hint">Film adds contrast, Lighter lifts the darks, Softer is mild.</p>
        </div>
        <div class="hb-setting" id="color-setting">
          <label class="hb-switch-row"><span>Colored grain</span><input class="hb-switch" type="checkbox" role="switch" id="color-tog" autocomplete="off"></label>
          <p class="hb-hint">Colored dots instead of gray ones.</p>
        </div>
        <div class="hb-setting">
          <p class="hb-setting-name" id="src-lbl">Grain source</p>
          <div class="seg" id="src-seg" role="group" aria-labelledby="src-lbl">
            <button type="button" data-impl="canvas" class="on" aria-pressed="true">Random dots</button>
            <button type="button" data-impl="svgfilter" aria-pressed="false">Noise filter</button>
          </div>
          <p class="hb-hint">Dots drawn by a script, or the browser's noise filter.</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 film grain overlay to [the section or page you want to texture]. Cover it with a see-through layer of random light and dark dots, and draw a new set of dots again and again so the grain flickers like old film; grain works best when it is felt more than seen. Blend the layer into the picture beneath it instead of laying gray on top, and let clicks pass through it. Redraw less often on phones, where drawing every dot is the costly part. If the visitor has reduced motion turned on, show the grain still. 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>Editorial sites</li><li>Portfolios</li><li>Photo and film pages</li><li>Hero sections</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Small text</li><li>Forms</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 cvs=document.getElementById('grain-cvs'),ctx=cvs.getContext('2d');
  const stage=document.querySelector('.stage');
  const slowTog=document.getElementById('slow-tog');
  const canvasWrap=document.getElementById('grain-canvas-wrap'),filterWrap=document.getElementById('grain-filter-wrap');
  const svgTurb=document.getElementById('grain-turb');
  const sizeSetting=document.getElementById('size-setting'),colorSetting=document.getElementById('color-setting');
  const vars=document.documentElement.style;
  const FILM_MS=1000/24; // phones change the grain at most this often
  const SLACK=2;         // a frame that arrives a hair early still counts, so "Every frame" is every frame
  const phone=matchMedia('(max-width:600px),(max-height:500px)'); // phones and short screens change the grain at most 24 times a second
  let W=0,H=0,raf=null,lastFrame=null;
  let IMPL='canvas',SIZE=2,COLOR_NOISE=false,frameInterval=FILM_MS,seed=0;
  // See inside and Compare: the band of plain grain (a copy of the real canvas's top rows), the scene's copy for Compare's first half,
  // the words, and what they depend on
  const world=document.getElementById('world'),worldA=document.getElementById('world-a');
  const band=document.getElementById('band'),bcvs=document.getElementById('band-cvs'),bctx=bcvs.getContext('2d'),bsvg=band.querySelector('.bsvg');
  const capBand=document.getElementById('cap-band'),capLaid=document.getElementById('cap-laid'),nameA=document.querySelector('.hn.a');
  const notes={inside:document.querySelector('[data-hb-for="inside"]'),compare:document.querySelector('[data-hb-for="compare"]')};
  const DASH=2,ZOOM=4; // the band's dashed edge (CSS) and the magnification (CSS --zoom)
  const OP_WORDS={'0.04':'a twenty-fifth','0.08':'a twelfth','0.16':'a sixth'};
  const BLEND_WORDS={overlay:'adding contrast',screen:'lifting the darks','soft-light':'mildly'};
  let mode='normal',paused=false,OP='0.08',BLEND='overlay';
  const copy=world.querySelector('.scene').cloneNode(true); // made once: Compare's first half, the scene without grain
  copy.setAttribute('inert','');copy.setAttribute('aria-hidden','true');worldA.appendChild(copy);

  function drawCanvasGrain(){
    if(!W||!H)return;
    const img=ctx.createImageData(W,H),data=img.data;
    for(let y=0;y<H;y+=SIZE)for(let x=0;x<W;x+=SIZE){
      // one color per grain dot: gray, or three random channels
      const v=Math.random()*255|0;
      const r=COLOR_NOISE?Math.random()*255|0:v;
      const g=COLOR_NOISE?Math.random()*255|0:v;
      const b=COLOR_NOISE?Math.random()*255|0:v;
      for(let dy=0;dy<SIZE&&y+dy<H;dy++)for(let dx=0;dx<SIZE&&x+dx<W;dx++){
        const idx=((y+dy)*W+(x+dx))*4;
        data[idx]=r;data[idx+1]=g;data[idx+2]=b;data[idx+3]=255;
      }
    }
    ctx.putImageData(img,0,0);
    copyBand();
  }
  // The band shows the top rows of the grain just drawn, pixel for pixel (never scaled, or fine dots would blur into gray)
  function copyBand(){
    if(mode==='inside'&&IMPL==='canvas'&&bcvs.width===W&&bcvs.height)bctx.drawImage(cvs,0,0,W,bcvs.height,0,0,W,bcvs.height);
  }
  // One new frame of grain from whichever source is showing
  function newGrain(){
    if(IMPL==='canvas')drawCanvasGrain();
    else{seed++;svgTurb.setAttribute('seed',seed)}
  }

  // Setting the canvas size wipes it, so a real change of the stage's size draws new grain at once, playing or paused.
  // A resize that leaves the stage as it was (a phone's address bar sliding in or out) does nothing.
  function resize(){
    const w=stage.clientWidth,h=stage.clientHeight;
    if(w===W&&h===H)return;
    W=cvs.width=w;H=cvs.height=h;
    layout();
    newGrain();
  }

  // The time between new grain frames: the chosen rate (phones: no faster than film), three times longer in slow motion
  function interval(){
    const ms=phone.matches?Math.max(frameInterval,FILM_MS):frameInterval;
    return slowTog.checked?ms*3:ms;
  }
  // loop() keeps exactly one frame requested in raf; Pause cancels it and Play starts one loop again.
  function loop(ts){
    raf=requestAnimationFrame(loop);
    // each new frame is due one interval after the last was due, so the rate holds on any screen; a long gap starts afresh
    const iv=interval();
    if(lastFrame===null||ts-lastFrame>=iv-SLACK){lastFrame=lastFrame===null||ts-lastFrame>=iv*2?ts:lastFrame+iv;newGrain()}
  }
  function start(){if(raf)return;lastFrame=null;raf=requestAnimationFrame(loop)}

  // Registered at the top level, before the shared script (deferred) can run: under reduced motion it pauses the
  // loop on arrival, which this listener must catch. The grain on screen stays as it is while paused.
  document.addEventListener('hb:pause',e=>{
    paused=e.detail.paused;
    if(paused){cancelAnimationFrame(raf);raf=null}
    else start();
    words();
  });
  // The mode switch draws the mode at once: the band copies the grain on screen (no new grain is drawn), Compare lines its windows up
  document.addEventListener('hb:mode',e=>{mode=e.detail.mode;words()});

  // The band is a third of the box (a quarter on phones); Compare's windows show the scene magnified around the eyebrow, below the names
  function layout(){
    if(!W||!H)return;
    if(mode==='inside'){
      const top=world.querySelector('.hero-label').offsetTop-8; // the band ends above the eyebrow where it can
      const bh=Math.max(Math.round(H*.2),capBand.offsetHeight+16,Math.min(Math.round(H*(phone.matches?.25:1/3)),top));
      band.style.height=bh+'px';bsvg.style.height=H+'px';
      if(bcvs.width!==W||bcvs.height!==bh-DASH){bcvs.width=W;bcvs.height=bh-DASH}
      copyBand();
    }else if(mode==='compare'){
      for(const el of [worldA,world]){el.style.setProperty('--sw',W+'px');el.style.setProperty('--sh',H+'px')} // the scene lays out at the box's size first
      const lab=world.querySelector('.hero-label'),px=lab.offsetLeft+lab.offsetWidth/2,py=lab.offsetTop+lab.offsetHeight/2;
      // the eyebrow sits low in the window, so the heading's top stays out of it and the room above shows plain gradient
      const heading=world.querySelector('.hero-h'),wl=Math.floor(W/2),top=8+nameA.offsetHeight+6;
      const ty=Math.max(top+30,H-(heading.offsetTop-py)*ZOOM-6)-ZOOM*py;
      for(const [el,wd] of [[worldA,wl],[world,W-wl]]){
        el.style.setProperty('--tx',(wd/2-ZOOM*px)+'px');el.style.setProperty('--ty',ty+'px');
      }
    }
  }
  // The words that depend on the settings, and whether the grain moves. A text is written only when it changes; the band and the
  // windows are lined up again after it, because the caption's height and the names' height depend on the words.
  function say(el,t){if(el.textContent!==t)el.textContent=t}
  function words(){
    const dots=IMPL==='canvas',strong=OP==='0.16',r=1000/interval();
    say(capBand,'The grain on its own: '+(dots?'random dots':'a noise texture')+', '+(paused?'held still':r>=59?'new ones every frame':r<1.7?'new ones about once a second':'new ones '+Math.round(r)+' times a second'));
    say(capLaid,'Laid over the page at '+OP_WORDS[OP]+' of that strength, '+BLEND_WORDS[BLEND]);
    const laid=strong?'at a sixth of that strength':null,sp=dots?'dots':'noise';
    say(notes.inside,paused
      ?'Inside, shown still: the top band is the grain on its own at full strength; below, the same grain laid over the page, '+(laid||'so faint you barely see it')+'.'
      :'Inside, the top band shows the grain on its own at full strength: '+(dots?'random dots that keep':'a noise texture that keeps')+' changing. Below, the same grain is laid over the page '+(laid||'so faintly you barely see it')+'.');
    say(notes.compare,(paused?'Shown still, both halves zoomed in and brightened':'Both halves are zoomed in and brightened')+' on the same spot: Without grain is smooth, while With grain'
      +(strong?', at Strong, shows its '+(paused?'':'flickering ')+sp+' plainly.'
        :' adds faint '+(paused?'':'flickering ')+sp+', felt more than seen. Pick Strong in Try it to see '+(dots?'them':'it')+' plainly.'));
    layout();
  }

  function choices(id,pick){
    const buttons=document.querySelectorAll('#'+id+' button');
    buttons.forEach(b=>b.addEventListener('click',()=>{
      if(b.classList.contains('on'))return; // pressing the choice already made does nothing
      buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
      pick(b.dataset);
    }));
  }
  // Strength and Blend are CSS and show at once; the settings that change how the grain is drawn draw one new frame,
  // so the change shows even while the loop is paused.
  choices('str-seg',d=>{vars.setProperty('--grain-op',d.op);OP=d.op;words()});
  choices('size-seg',d=>{SIZE=+d.px;newGrain()});
  choices('rate-seg',d=>{frameInterval=1000/+d.fps;words()});
  choices('blend-seg',d=>{vars.setProperty('--grain-blend',d.blend);BLEND=d.blend;words()});
  document.getElementById('color-tog').addEventListener('change',e=>{COLOR_NOISE=e.target.checked;newGrain()});
  choices('src-seg',d=>{
    IMPL=d.impl;
    canvasWrap.style.display=IMPL==='canvas'?'block':'none';
    filterWrap.style.display=IMPL==='svgfilter'?'block':'none';
    // Grain size and Colored grain only apply to the dots
    sizeSetting.hidden=colorSetting.hidden=IMPL!=='canvas';
    band.classList.toggle('svg',IMPL!=='canvas');
    newGrain();
    words();
  });

  slowTog.addEventListener('change',words);
  phone.addEventListener('change',words);
  document.fonts.ready.then(layout);
  resize();
  window.addEventListener('resize',resize);
  start();
</script>
</body>
</html>