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
feat: move Grain / Film Noise Overlay to the guided-steps page
matin6f4d1e746740
diff --git a/animations/07-ambient-background/grain-overlay/README.md b/animations/07-ambient-background/grain-overlay/README.mdindex e7aaf5fe..2a4fea0e 100644--- a/animations/07-ambient-background/grain-overlay/README.md+++ b/animations/07-ambient-background/grain-overlay/README.md@@ -1,7 +1,7 @@# Grain / Film Noise Overlay## What it is-Film grain adds organic texture to clean digital design by layering an animated noise pattern over the content at low opacity. The effect mimics the silver-halide crystal randomness of analog film photography. At the right intensity (5–10% opacity), it is nearly invisible but improves perceived depth and warmth. Above 20%, it reads as a damaged screen. The key to film grain is subtlety — users should not notice it, only notice when it's removed.+Film grain lays a see-through layer of random dots over a design and draws it again and again, so the texture flickers like the grain of photographic film. At a low strength, around 5 to 10 percent, it is barely visible, yet flat digital colors feel warmer and deeper; much stronger, and it looks like a damaged screen. The trick is subtlety: people should not notice the grain, only miss it when it is gone.## When to use it- Hero sections and portfolio pages where a photographic, editorial aesthetic is desired@@ -20,14 +20,15 @@ function drawGrain(canvas, ctx, pixelSize = 2, colorNoise = false) {for (let y = 0; y < H; y += pixelSize) {for (let x = 0; x < W; x += pixelSize) {+ // one color per grain dot: gray, or three random channelsconst v = Math.random() * 255 | 0;+ const r = colorNoise ? Math.random() * 255 | 0 : v;+ const g = colorNoise ? Math.random() * 255 | 0 : v;+ const b = colorNoise ? Math.random() * 255 | 0 : v;for (let dy = 0; dy < pixelSize && y + dy < H; dy++) {for (let dx = 0; dx < pixelSize && x + dx < W; dx++) {const idx = ((y + dy) * W + (x + dx)) * 4;- data[idx] = colorNoise ? (Math.random() * 255 | 0) : v;- data[idx + 1] = colorNoise ? (Math.random() * 255 | 0) : v;- data[idx + 2] = colorNoise ? (Math.random() * 255 | 0) : v;- data[idx + 3] = 255;+ data[idx] = r; data[idx + 1] = g; data[idx + 2] = b; data[idx + 3] = 255;}}}@@ -78,19 +79,22 @@ function loop() {## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|-| Intensity (opacity) | 8% | 5–10% = invisible but impactful; 15% = noticeable; 30% = distracting |-| Grain size (pixel size) | 2px | 1px = fine digital noise; 3px = coarse film grain; 4px+ = halftone |-| Update rate | 24fps | 24fps = film; 12fps = lo-fi analog; 60fps = digital video noise |-| Blend mode | overlay | `overlay` respects light/dark values; `screen` brightens; `soft-light` is subtler |+| Strength | Light | How visible the grain is: faint is 4%, light 8% and strong 16%; 5–10% is felt more than seen, above 20% it looks like a damaged screen |+| Grain size | Medium | The size of each dot: fine is 1px, medium 2px and coarse 3px; coarse looks like old film stock |+| How often it changes | Like film | New grain every frame (60 times a second), like film (24), choppy (12) or slow (4); phones change it at most 24 times a second |+| Blend | Film | How the grain mixes with the picture: film darkens dark areas and lightens light ones, like real grain (overlay blending); lighter only lightens (screen); softer is a gentler film (soft light) |+| Colored grain | off | Randomly colored dots instead of gray ones |+| Grain source | Random dots | Dots drawn by a script, or the browser's own noise filter; grain size and colored grain apply to the dots only |## Production notes- **Canvas vs SVG feTurbulence**: canvas gives more control (pixel size, color noise) but is more CPU-intensive. SVG feTurbulence is GPU-accelerated and simpler but offers less control over grain character.- **Reduced update rate is intentional**: real film grain is 24fps, not 60fps. Generating a new canvas texture 60 times per second is wasted computation — 12–24fps matches the aesthetic and reduces CPU load.+- **Phones**: the demo changes the grain at most 24 times a second on screens narrower than 600px, and draws the canvas at CSS pixels rather than device pixels; drawing every dot is the costly part.- **`mix-blend-mode: overlay`** is the standard for grain: it darkens dark areas slightly and brightens light areas slightly, matching how silver halide responds to exposure.- **CSS filter on a pseudo-element**: the cleanest production approach — add `::after { content:''; position:absolute; inset:0; background:url(grain.png); animation:grain 0.5s steps(1) infinite; }` with a spritesheet of pre-generated grain frames. This offloads grain generation entirely to a static asset.- **React libraries**: `react-noise` and various `css-grain` packages implement the SVG filter approach as zero-config drop-in components.## See also-- [Scanline](../scanline/) — another retro-analog overlay technique for CRT aesthetics-- [Chromatic Aberration](../../06-3d-advanced/chromatic-aberration/) — companion glitch effect for a degraded-media aesthetic-- [Light Leak](../light-leak/) — another film-photography-inspired ambient overlay+- [Scanline Effect](../scanline/) — dark lines over the page, like an old monitor+- [Chromatic Aberration](../../06-3d-advanced/chromatic-aberration/) — colors split at the edges, like a cheap lens+- [Light Leak](../light-leak/) — warm light washes in, like a film camera flawdiff --git a/animations/07-ambient-background/grain-overlay/index.html b/animations/07-ambient-background/grain-overlay/index.htmlindex 13d124e3..040c9a05 100644--- a/animations/07-ambient-background/grain-overlay/index.html+++ b/animations/07-ambient-background/grain-overlay/index.html@@ -4,7 +4,7 @@<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="Animated noise texture adds cinematic warmth — subtlety is everything. 5–10% opacity, not 30%.">+ <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">@@ -12,205 +12,262 @@<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="Animated noise texture adds cinematic warmth — subtlety is everything. 5–10% opacity, not 30%.">+ <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="Animated noise texture adds cinematic warmth — subtlety is everything. 5–10% opacity, not 30%.">+ <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": "Animated noise texture adds cinematic warmth — subtlety is everything. 5–10% opacity, not 30%.", "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>+ <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>- @font-face{font-family:'Bricolage';src:url('../../../assets/fonts/brico-700.woff2') format('woff2');font-weight:700;font-display:swap}- @font-face{font-family:'Bricolage';src:url('../../../assets/fonts/brico-800.woff2') format('woff2');font-weight:800;font-display:swap}- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-500.woff2') format('woff2');font-weight:500;font-display:swap}- :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#ffce5a;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px;--grain-op:0.08;--grain-blend:overlay}+ :root{--ui-accent:#ffce5a;--grain-op:0.08;--grain-blend:overlay}*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}- body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}- header{margin-bottom:20px}- header h1{font-family:var(--disp);font-weight:700;font-size:clamp(11px,1.8vw,15px);letter-spacing:-.01em}- header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}- .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}- .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative}+ .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:10px;letter-spacing:3px;text-transform:uppercase;color:rgba(88,166,255,.5);margin-bottom:12px}- .hero-h{font-family:Georgia,serif;font-size:clamp(22px,3.5vw,36px);color:#fff;font-style:italic;line-height:1.2;margin-bottom:12px}- .hero-p{font-size:12px;color:rgba(255,255,255,.5);line-height:1.7;max-width:280px;margin:0 auto}+ .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 */.grain-svg{display:none}/* 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%}- .fps-badge{position:absolute;top:8px;right:8px;font-size:9px;color:rgba(255,255,255,.4);background:rgba(0,0,0,.5);padding:3px 8px;border-radius:4px}/* 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)}- aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}- .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}- .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}- .div{height:1px;background:var(--ui-border)}- .sr{display:flex;align-items:center;gap:6px;font-size:10px}- .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}- .sv{width:44px;text-align:right;color:var(--ui-text)}- select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}- .tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}- .tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}- button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}- @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}- @media(max-width:600px){.layout{flex-direction:column;align-items:stretch}aside{width:100%}:root{--stage-h:auto}.stage{flex:none;height:auto;min-height:400px}}- /* Reduced motion: grain stays visible but is rendered once, never re-generated (see script). */</style>-<style id="ah-inject">-:root{--ah-bg:rgba(17,17,20,.82);--ah-line:rgba(255,255,255,.1);--ah-ink:#f4f4f2;--ah-muted:#9a9aa2;--ah-accent:#6ea8ff}-body{padding-top:46px}-.ah-bar{position:fixed;top:0;left:0;right:0;height:46px;z-index:2147483000;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:0 clamp(10px,3vw,18px);background:var(--ah-bg);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-bottom:1px solid var(--ah-line);font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;box-sizing:border-box}-.ah-bar a,.ah-bar button{color:var(--ah-muted);text-decoration:none;background:none;border:0;font:inherit;cursor:pointer;display:inline-flex;align-items:center;gap:6px;min-height:34px;padding:0 7px;border-radius:6px;transition:color .18s,background .18s;white-space:nowrap}-.ah-bar a:hover,.ah-bar button:hover{color:var(--ah-ink)}-.ah-home{color:var(--ah-ink);font-weight:600}-.ah-actions{display:flex;align-items:center;gap:2px}-.ah-sep{width:1px;height:16px;background:var(--ah-line);margin:0 4px}-.ah-copied{color:var(--ah-accent)!important}-@media(max-width:600px){.ah-bar .ah-hideSm{display:none}}-@media print{.ah-bar{display:none}body{padding-top:0}}-</style>+ <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=3">+ <script src="../../../assets/js/demo-page.js?v=3" defer></script></head>-<body>-<div class="ah-bar" role="navigation" aria-label="Animation Handbook"><a class="ah-home" href="../../../">← Animation Handbook</a><span class="ah-actions"><a class="ah-hideSm" href="../aurora/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../scanline/" rel="next" title="Next">Next ›</a><span class="ah-sep ah-hideSm"></span><button type="button" id="ah-copy" class="ah-hideSm">Copy source</button><a class="ah-hideSm" href="https://github.com/matinmonshizadeh/animation-handbook/blob/main/animations/07-ambient-background/grain-overlay/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>-<header>- <h1>Grain / Film Noise Overlay</h1>- <p>Animated noise texture adds cinematic warmth — subtlety is everything. 5–10% opacity, not 30%.</p>-</header>-<div class="layout">- <div class="stage" id="stage">- <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>+<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>+</nav>+<main class="hb-page">+ <header class="hb-head">+ <p class="hb-cat">07.04 · Ambient & 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="stage">+ <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%"><feTurbulence type="fractalNoise" baseFrequency="0.65" numOctaves="3" stitchTiles="stitch" id="grain-turb"/><feColorMatrix type="saturate" values="0"/></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>- <!-- SVG filter fallback -->- <svg class="grain-svg" style="display:none"><defs><filter id="grain-filter" x="0%" y="0%" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="0.65" numOctaves="3" stitchTiles="stitch" id="grain-turb"/><feColorMatrix type="saturate" values="0"/></filter></defs></svg>- <div class="grain-filter-wrap" id="grain-filter-wrap"><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"><canvas id="grain-cvs"></canvas></div>- <div class="fps-badge" id="fps">— fps</div>- </div>- <aside>- <p class="note">Grain at 30%+ opacity looks like a broken screen. At 5–10% it improves perceived quality without being visible. Real film grain is 24fps — slower feels more cinematic.</p>- <div class="lbl">Implementation</div>- <select id="impl-sel">- <option value="canvas" selected>Canvas (regen)</option>- <option value="svgfilter">SVG feTurbulence</option>- </select>- <div class="lbl">Intensity</div>- <div class="sr"><input type="range" id="int-sl" min="2" max="30" value="8" step="1"><span class="sv" id="int-v">8%</span></div>- <div class="lbl">Grain Size</div>- <select id="size-sel">- <option value="1">Fine (1px)</option>- <option value="2" selected>Medium (2px)</option>- <option value="3">Coarse (3px)</option>- </select>- <div class="lbl">Update Rate</div>- <select id="rate-sel">- <option value="60" selected>60fps (digital)</option>- <option value="24">24fps (film)</option>- <option value="12">12fps (lo-fi)</option>- <option value="4">4fps (analog)</option>- </select>- <div class="lbl">Blend Mode</div>- <select id="blend-sel">- <option value="overlay" selected>Overlay</option>- <option value="screen">Screen</option>- <option value="soft-light">Soft-light</option>- </select>- <label class="tog"><input type="checkbox" id="color-tog"><span>Color noise (RGB)</span></label>- <div class="div"></div>- <div style="font-size:9px;color:var(--ui-muted)">Render: <span id="fps2">—</span> fps</div>- <button class="rst" id="pause-btn">⏸ Pause</button>- </aside>-</div>-<script>-const cvs=document.getElementById('grain-cvs'),ctx=cvs.getContext('2d');-const stage=document.getElementById('stage');-const fpsEl=document.getElementById('fps'),fps2El=document.getElementById('fps2');-let W,H,paused=false,raf=null,lastFrame=0,lastT=0;-let IMPL='canvas',SIZE=2,RATE=60,COLOR_NOISE=false,INTENSITY=0.08;-let frameInterval=1000/60;-let svgTurb=document.getElementById('grain-turb');-let seed=0;-const reduceMQ=window.matchMedia('(prefers-reduced-motion: reduce)');+ <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>+ </section>-function resize(){- W=cvs.width=stage.clientWidth;H=cvs.height=stage.clientHeight;- // width/height assignment wipes the canvas — repaint if the loop won't- if((paused||reduceMQ.matches)&&IMPL==='canvas')drawCanvasGrain();-}-resize();window.addEventListener('resize',resize);+ <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>-function drawCanvasGrain(){- const img=ctx.createImageData(W,H);const data=img.data;- const step=SIZE;- for(let y=0;y<H;y+=step)for(let x=0;x<W;x+=step){- const v=Math.random()*255|0;- for(let dy=0;dy<step&&y+dy<H;dy++)for(let dx=0;dx<step&&x+dx<W;dx++){- const idx=(y+dy)*W*4+(x+dx)*4;- if(COLOR_NOISE){data[idx]=Math.random()*255|0;data[idx+1]=Math.random()*255|0;data[idx+2]=Math.random()*255|0;}- else{data[idx]=v;data[idx+1]=v;data[idx+2]=v;}- data[idx+3]=255;+ <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>+ </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="#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+ let W=0,H=0,raf=null,lastFrame=null;+ let IMPL='canvas',SIZE=2,COLOR_NOISE=false,frameInterval=FILM_MS,seed=0;++ 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);+ }+ // One new frame of grain from whichever source is showing+ function newGrain(){+ if(IMPL==='canvas')drawCanvasGrain();+ else{seed++;svgTurb.setAttribute('seed',seed)}}- ctx.putImageData(img,0,0);-}-// One frame of grain, then stop — the texture is still there, it just never moves.-function renderStatic(){- if(IMPL==='canvas')drawCanvasGrain();- else svgTurb.setAttribute('seed',seed);- fpsEl.textContent='static';fps2El.textContent='0';-}+ // 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;+ newGrain();+ }-function loop(ts){- if(paused){raf=null;return;}- if(reduceMQ.matches){raf=null;renderStatic();return;}- raf=requestAnimationFrame(loop);- const dt=ts-lastT;if(dt<10)return;- const f=Math.round(1000/(dt||16));fpsEl.textContent=f+' fps';fps2El.textContent=f;lastT=ts;- if(ts-lastFrame>=frameInterval){- lastFrame=ts;- if(IMPL==='canvas')drawCanvasGrain();- else{seed++;svgTurb.setAttribute('seed',seed);}+ // The time between new grain frames: the chosen rate (phones: no faster than film), three times longer in slow motion+ function interval(){+ const ms=W<600?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);+ if(lastFrame===null||ts-lastFrame>=interval()-SLACK){lastFrame=ts;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=>{+ if(e.detail.paused){cancelAnimationFrame(raf);raf=null}+ else start();+ });-loop(performance.now());+ 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);+ }));+ }+ // 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)});+ choices('size-seg',d=>{SIZE=+d.px;newGrain()});+ choices('rate-seg',d=>{frameInterval=1000/+d.fps});+ choices('blend-seg',d=>{vars.setProperty('--grain-blend',d.blend)});+ 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';+ newGrain();+ });-document.getElementById('impl-sel').addEventListener('change',e=>{- IMPL=e.target.value;- document.getElementById('grain-canvas-wrap').style.display=IMPL==='canvas'?'block':'none';- document.getElementById('grain-filter-wrap').style.display=IMPL==='svgfilter'?'block':'none';- if(reduceMQ.matches)renderStatic();-});-document.getElementById('int-sl').addEventListener('input',e=>{- INTENSITY=e.target.value/100;document.getElementById('int-v').textContent=e.target.value+'%';- document.documentElement.style.setProperty('--grain-op',INTENSITY);-});-document.getElementById('size-sel').addEventListener('change',e=>{SIZE=+e.target.value;if(reduceMQ.matches)renderStatic();});-document.getElementById('rate-sel').addEventListener('change',e=>{frameInterval=1000/+e.target.value;});-document.getElementById('blend-sel').addEventListener('change',e=>{document.documentElement.style.setProperty('--grain-blend',e.target.value);});-document.getElementById('color-tog').addEventListener('change',e=>{COLOR_NOISE=e.target.checked;if(reduceMQ.matches)renderStatic();});-document.getElementById('pause-btn').addEventListener('click',()=>{- paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';- if(!paused){lastT=performance.now();raf=requestAnimationFrame(loop);}-});-reduceMQ.addEventListener('change',()=>{- if(reduceMQ.matches)renderStatic();- else if(!paused&&!raf){lastT=performance.now();raf=requestAnimationFrame(loop);}-});+ resize();+ window.addEventListener('resize',resize);+ start();</script>-<script>(function(){var b=document.getElementById("ah-copy");if(!b)return;b.addEventListener("click",function(){fetch(location.href).then(function(r){return r.text();}).catch(function(){return document.documentElement.outerHTML;}).then(function(t){return navigator.clipboard.writeText(t);}).then(function(){b.textContent="Copied!";b.classList.add("ah-copied");setTimeout(function(){b.textContent="Copy source";b.classList.remove("ah-copied");},1500);}).catch(function(){b.textContent="Copy failed";setTimeout(function(){b.textContent="Copy source";},1500);});});})();</script></body></html>diff --git a/index.html b/index.htmlindex 9aa535a1..a81399bb 100644--- a/index.html+++ b/index.html@@ -1036,7 +1036,7 @@ const CATS=[['animated-gradient-background','Animated Gradient Background','Colors slowly drift across a soft gradient background. Best for hero sections.'],['mesh-gradient','Mesh Gradient Animation','Blurred blobs of color drift and melt together. Best for landing pages.'],['aurora','Aurora / Northern Lights','Blurred bands of light sway like the northern lights. Best for dark backgrounds.'],- ['grain-overlay','Grain / Film Noise Overlay','Animated noise at 5–10% opacity adds cinematic warmth — subtlety is everything.'],+ ['grain-overlay','Grain / Film Noise Overlay','Fine grain flickers over the page, like old film. Best for editorial sites.'],['scanline','Scanline Effect','CRT horizontal lines with optional sweep beam, curvature, and phosphor glow.'],['light-leak','Light Leak','Warm gradient fires at random irregular intervals — analog film camera aesthetic.'],['starfield','Starfield / Space Particles','Stars drift outward from center with parallax depth — slow ambient speed, never hyperspace.'],