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 Matrix Rain to the guided-steps page
matinb71778f3b81c
diff --git a/animations/07-ambient-background/matrix-rain/README.md b/animations/07-ambient-background/matrix-rain/README.mdindex 0a7df38c..191b656b 100644--- a/animations/07-ambient-background/matrix-rain/README.md+++ b/animations/07-ambient-background/matrix-rain/README.md@@ -1,7 +1,7 @@# Matrix Rain## What it is-Matrix rain — also called "digital rain" — is an ambient background of vertical columns of characters falling down a dark surface. The leading glyph in each column is bright, and the characters behind it fade toward black, giving the impression of a glowing head trailing a tail. It became a cultural shorthand for "computers doing something" after appearing in *The Matrix* (1999), and is drawn on a `<canvas>` because the per-frame character churn is too heavy for the DOM.+Matrix rain, also called digital rain, is a background of columns of characters falling down a dark screen. The leading character in each column is bright and the ones behind it fade toward black, so each column looks like a glowing head with a fading tail. It became shorthand for "computers at work" after the film The Matrix (1999).## When to use it- Terminal, hacker, or "system online" themed landing pages and hero sections@@ -10,7 +10,7 @@ Matrix rain — also called "digital rain" — is an ambient background of verti- Music visualizers and demo-scene style ambient loops## How it works-Each column tracks a single vertical position (its "drop"). Every step, the column draws a fresh bright character at its head, then advances one row. The trail is not stored — it is produced by painting a translucent black rectangle over the entire canvas each frame, which darkens every previously drawn glyph a little more until it disappears:+Each column tracks a single vertical position (its "drop"). Every step, the column draws a fresh bright character at its head, then advances one row. The trail is not stored — it is produced by painting a translucent black rectangle over the entire canvas each step, which darkens every previously drawn glyph a little more until it disappears:```js// Fade the whole canvas slightly instead of clearing it.@@ -22,7 +22,7 @@ for (let i = 0; i < cols; i++) {const x = i * pitch, y = drops[i] * fontSize;ctx.fillStyle = '#d8ffe6'; // bright leaderctx.fillText(pick(), x, y);- if (y > H && Math.random() > 0.975) drops[i] = 0; // recycle randomly+ if (y > H && Math.random() > 0.975) drops[i] = Math.floor(Math.random() * -20); // back above the top, at randomdrops[i]++; // fall one row}```@@ -32,20 +32,20 @@ Because the canvas is never fully cleared, the length of the tail is entirely co## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|-| Speed | 8 | Steps per second scalar. Low = slow drizzle; high = dense downpour |-| Font size | 16px | Glyph size; also sets column width, so larger = fewer columns |-| Trail fade | 0.07 | Per-frame black opacity. 0.02 = long ghostly tails; 0.20 = short crisp heads |-| Character set | Katakana | Katakana (classic), Binary (0/1), or Hex (0–F) |-| Leader glow | on | `shadowBlur` halo on the head glyph for a phosphor bloom |+| Speed | Normal | How often the rain moves down a row: slow is about 18 times a second, normal 28 and fast about 46 |+| Characters | Japanese | Japanese katakana (the film's look), binary 0 and 1, or hexadecimal 0 to F |+| Trail length | Medium | How long characters linger: short fades 12% a step, medium 7% and long 4% |+| Character size | Medium | Small is 12px, medium 16px and large 22px; larger characters make fewer columns |+| Glowing leaders | on | A soft glow around each column's leading character |## Production notes- **`fillRect` fade vs `clearRect`**: clearing the canvas each frame gives no trail — you would have to store and redraw every past glyph yourself. Painting a translucent `fillRect` is both the trail mechanism and cheaper, since it is one composited rectangle instead of hundreds of retained cells.- **Cap density on mobile**: column count is derived from a minimum pixel pitch, not an unbounded `width / fontSize`. Combined with clamping `devicePixelRatio` to 2, this keeps the per-frame `fillText` count bounded so the effect holds 60fps on mid-range phones. Heavy `shadowBlur` is the most expensive part — it is applied only to the single leader glyph, never the trail.- **Pause on hidden tab**: the `requestAnimationFrame` loop is cancelled on `visibilitychange` when `document.hidden` is true and restarted when the tab returns, so a background tab burns no CPU or battery.-- **Reduced motion**: under `prefers-reduced-motion: reduce` the animation loop never starts — a single static frame is rendered once so the effect is still legible without any movement.+- **Reduced motion**: the demo starts paused, showing a screen of rain drawn at once, until the visitor presses Play. In production, show these visitors a still frame.- **It is decorative**: real usage should sit behind content with `aria-hidden="true"`, `pointer-events: none`, and enough contrast on the foreground text that the rain does not reduce readability. Treat it as texture, not information.## See also-- [Starfield](../starfield/) — canvas particle field with parallax depth-- [Scanline](../scanline/) — CRT line overlay for the same retro-terminal mood-- [Synthwave Grid](../synthwave-grid/) — perspective neon grid for cyberpunk backdrops+- [Starfield / Space Particles](../starfield/) — another canvas background of moving points+- [Scanline Effect](../scanline/) — dark lines for the same old-terminal mood+- [Synthwave Grid](../synthwave-grid/) — a neon grid for a retro-future backdropdiff --git a/animations/07-ambient-background/matrix-rain/index.html b/animations/07-ambient-background/matrix-rain/index.htmlindex 4280e819..e9610049 100644--- a/animations/07-ambient-background/matrix-rain/index.html+++ b/animations/07-ambient-background/matrix-rain/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Matrix Rain — Animation Handbook</title>- <meta name="description" content="Columns of glowing characters fall down a dark canvas — bright leaders, fading trails.">+ <meta name="description" content="Columns of glowing characters rain down a dark screen. Best for tech themes."><link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/matrix-rain/"><link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png"><link rel="icon" type="image/svg+xml" href="../../../favicon.svg">@@ -12,187 +12,263 @@<meta property="og:type" content="article"><meta property="og:site_name" content="Animation Handbook"><meta property="og:title" content="Matrix Rain — Animation Handbook">- <meta property="og:description" content="Columns of glowing characters fall down a dark canvas — bright leaders, fading trails.">+ <meta property="og:description" content="Columns of glowing characters rain down a dark screen. Best for tech themes."><meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/matrix-rain/"><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="Matrix Rain — Animation Handbook">- <meta name="twitter:description" content="Columns of glowing characters fall down a dark canvas — bright leaders, fading trails.">+ <meta name="twitter:description" content="Columns of glowing characters rain down a dark screen. Best for tech themes."><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": "Matrix Rain", "name": "Matrix Rain", "description": "Columns of glowing characters fall down a dark canvas — bright leaders, fading trails.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/matrix-rain/", "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, Matrix Rain"}</script>+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Matrix Rain", "name": "Matrix Rain", "description": "Columns of glowing characters rain down a dark screen. Best for tech themes.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/matrix-rain/", "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, Matrix Rain"}</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:#5fd88a;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px}+ :root{--ui-accent:#ffce5a}*,*::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-wrap{flex:1;min-width:0}- .stage{height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;overflow:hidden;position:relative;background:#000}+ .stage{position:relative;overflow:hidden;background:#000}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;pointer-events:none}- 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:40px;text-align:right;color:var(--ui-text)}- select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;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:monospace;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}aside{width:100%}:root{--stage-h:380px}- .tog input{width:44px;height:44px}}</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="../synthwave-grid/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../plasma/" 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/matrix-rain/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>-<header>- <h1>Matrix Rain</h1>- <p>Columns of glowing characters fall down a dark canvas — bright leaders, fading trails.</p>-</header>-<div class="layout">- <div class="stage-wrap">- <div class="stage" id="stage">- <canvas id="cvs"></canvas>- <div class="fps-badge" id="fps">— fps</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="../synthwave-grid/" rel="prev" aria-label="Previous: Synthwave Grid"><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>Synthwave Grid</span></a><a href="../plasma/" rel="next" aria-label="Next: Plasma Field"><span><span class="hb-dir">Next: </span>Plasma Field</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.16 · Ambient & Background</p>+ <h1>Matrix Rain</h1>+ <p class="hb-lede">Columns of glowing characters rain down a dark screen. Best for tech themes.</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>- <aside>- <p class="note">Each column drops one bright character per step. A translucent black rectangle painted every frame fades old characters into the trail — never cleared, so the tail length is a function of the fade opacity.</p>- <div class="lbl">Speed</div>- <div class="sr"><input type="range" id="spd-sl" min="1" max="20" value="8" step="1"><span class="sv" id="spd-v">8</span></div>- <div class="lbl">Font size</div>- <div class="sr"><input type="range" id="fs-sl" min="10" max="28" value="16" step="2"><span class="sv" id="fs-v">16</span></div>- <div class="lbl">Trail fade</div>- <div class="sr"><input type="range" id="fade-sl" min="2" max="20" value="7" step="1"><span class="sv" id="fade-v">.07</span></div>- <div class="lbl">Characters</div>- <select id="set-sel">- <option value="kana" selected>Katakana</option>- <option value="bin">Binary</option>- <option value="hex">Hexadecimal</option>- </select>- <label class="tog"><input type="checkbox" id="glow-tog" checked><span>Leader glow</span></label>- <div class="div"></div>- <div style="font-size:9px;color:var(--ui-muted)" id="fps-note">FPS: <span id="fps2">—</span></div>- <button class="rst" id="pause-btn">⏸ Pause</button>- </aside>-</div>-<script>-const cvs=document.getElementById('cvs'),ctx=cvs.getContext('2d');-const stage=document.getElementById('stage');-const fpsEl=document.getElementById('fps'),fps2=document.getElementById('fps2');-const reduced=window.matchMedia('(prefers-reduced-motion: reduce)').matches;-const SETS={- kana:'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワ0123456789',- bin:'01',- hex:'0123456789ABCDEF'-};-let W,H,dpr=1,cols=0,drops=[],fontSize=16;-let paused=false,raf=null,lastT=0,acc=0;-let SPD=8,FADE=.07,SET='kana',GLOW=true;+ <div class="stage">+ <canvas id="cvs" aria-hidden="true"></canvas>+ </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>+ </section>-function resize(){- dpr=Math.min(window.devicePixelRatio||1,2);- const cw=stage.clientWidth,ch=stage.clientHeight;- cvs.width=Math.round(cw*dpr);cvs.height=Math.round(ch*dpr);- W=cw;H=ch;- ctx.setTransform(dpr,0,0,dpr,0,0);- // Cap columns on small screens: enforce a minimum column pitch.- const pitch=Math.max(fontSize,W<600?14:11);- cols=Math.floor(W/pitch);- drops=Array.from({length:cols},()=>Math.floor(Math.random()*-H/fontSize));- ctx.fillStyle='#000';ctx.fillRect(0,0,W,H);-}+ <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="speed-lbl">Speed</p>+ <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">+ <button type="button" data-spd="5" aria-pressed="false">Slow</button>+ <button type="button" data-spd="8" class="on" aria-pressed="true">Normal</button>+ <button type="button" data-spd="13" aria-pressed="false">Fast</button>+ </div>+ <p class="hb-hint">Slow is a drizzle; fast is a downpour.</p>+ </div>+ <div class="hb-setting">+ <p class="hb-setting-name" id="set-lbl">Characters</p>+ <div class="seg" id="set-seg" role="group" aria-labelledby="set-lbl">+ <button type="button" data-set="kana" class="on" aria-pressed="true">Japanese</button>+ <button type="button" data-set="bin" aria-pressed="false">Binary</button>+ <button type="button" data-set="hex" aria-pressed="false">Hexadecimal</button>+ </div>+ <p class="hb-hint">Japanese characters give the film's look.</p>+ </div>+ <div class="hb-setting">+ <p class="hb-setting-name" id="fade-lbl">Trail length</p>+ <div class="seg" id="fade-seg" role="group" aria-labelledby="fade-lbl">+ <button type="button" data-fade="0.12" aria-pressed="false">Short</button>+ <button type="button" data-fade="0.07" class="on" aria-pressed="true">Medium</button>+ <button type="button" data-fade="0.04" aria-pressed="false">Long</button>+ </div>+ <p class="hb-hint">How long characters linger behind each leader.</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="size-lbl">Character size</p>+ <div class="seg" id="size-seg" role="group" aria-labelledby="size-lbl">+ <button type="button" data-px="12" aria-pressed="false">Small</button>+ <button type="button" data-px="16" class="on" aria-pressed="true">Medium</button>+ <button type="button" data-px="22" aria-pressed="false">Large</button>+ </div>+ <p class="hb-hint">Larger characters make fewer, wider columns.</p>+ </div>+ <div class="hb-setting">+ <label class="hb-switch-row"><span>Glowing leaders</span><input class="hb-switch" type="checkbox" role="switch" id="glow-tog" checked autocomplete="off"></label>+ <p class="hb-hint">The leading character in each column glows.</p>+ </div>+ </div>+ </details>+ </section>-function pick(){const s=SETS[SET];return s[Math.floor(Math.random()*s.length)];}+ <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 matrix rain background to [the section you want it behind]. Split a dark canvas into columns and, at a steady pace, draw a bright character at the head of each column and move it down one row, sending each column back to the top at random once it passes the bottom. Instead of clearing the canvas, cover it with a see-through black layer before each step, so older characters fade into a trail behind each bright leader. Space the columns wider on phones. If the visitor has reduced motion turned on, show one still frame. 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>Tech and hacker themes</li><li>Loading screens</li><li>Game and event pages</li><li>404 pages</li></ul>+ <h3>Avoid on</h3>+ <ul class="hb-tags hb-avoid"><li>Calm brands</li><li>Long reading pages</li></ul>+ </div>+ </section>-function step(){- // Translucent fade: paint semi-opaque black over the whole canvas each frame- // so previously drawn glyphs decay into the trail instead of being cleared.- ctx.fillStyle='rgba(0,0,0,'+FADE+')';- ctx.fillRect(0,0,W,H);- ctx.font=fontSize+'px '+getComputedStyle(document.body).getPropertyValue('--mono');- ctx.textBaseline='top';- const pitch=W/cols;- for(let i=0;i<cols;i++){- const x=i*pitch,y=drops[i]*fontSize;- if(GLOW){ctx.shadowColor='#5fd88a';ctx.shadowBlur=8;}else{ctx.shadowBlur=0;}- ctx.fillStyle='#d8ffe6';ctx.fillText(pick(),x,y); // bright leader- ctx.shadowBlur=0;- ctx.fillStyle='#3aa564';ctx.fillText(pick(),x,y-fontSize); // dimmer follower- if(y>H&&Math.random()>.975)drops[i]=Math.floor(Math.random()*-20);- drops[i]++;+ <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('cvs'),ctx=cvs.getContext('2d');+ const stage=document.querySelector('.stage');+ const slowTog=document.getElementById('slow-tog');+ const SETS={+ kana:'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワ0123456789',+ bin:'01',+ hex:'0123456789ABCDEF'+ };+ // The page's own font, read once. The Japanese characters come from the system's fallback font, as the site font has none.+ const FONT=getComputedStyle(document.body).fontFamily;+ const phone=matchMedia('(max-width:600px),(max-height:500px)'); // phones and short screens space the columns wider+ let W=0,H=0,dpr=1,cols=0,drops=[],fontSize=16;+ let raf=null,last=null,acc=0,paused=false,unseen=false;+ let SPD=8,FADE=.07,SET='kana',GLOW=true;++ function colsFor(w){return Math.floor(w/Math.max(fontSize,phone.matches?14:11));}++ // Every column starts above the top edge, on a black canvas.+ function deal(){+ drops=Array.from({length:cols},()=>Math.floor(Math.random()*-H/fontSize));+ ctx.fillStyle='#000';ctx.fillRect(0,0,W,H);}-}+ // The canvas takes the stage's size, which also wipes it: new columns, every drop above the top, a black canvas.+ function resize(){+ dpr=Math.min(window.devicePixelRatio||1,2);+ W=stage.clientWidth;H=stage.clientHeight;+ cvs.width=Math.round(W*dpr);cvs.height=Math.round(H*dpr);+ ctx.setTransform(dpr,0,0,dpr,0,0);+ cols=colsFor(W);+ deal();+ }++ function pick(){const s=SETS[SET];return s[Math.floor(Math.random()*s.length)];}-// Every column starts above the top edge, so one step paints an empty canvas.-// Run enough steps for each column to enter view and grow its trail.-function paintStatic(){const n=Math.ceil(H/fontSize)+20;for(let i=0;i<n;i++)step();}+ // One step: dim the whole canvas a little instead of clearing it, so older characters decay into the trail, then draw+ // a bright leader and a dimmer character above it in every column and move the column down a row.+ function step(){+ ctx.fillStyle='rgba(0,0,0,'+FADE+')';+ ctx.fillRect(0,0,W,H);+ ctx.font=fontSize+'px '+FONT;+ ctx.textBaseline='top';+ const pitch=W/cols;+ for(let i=0;i<cols;i++){+ const x=i*pitch,y=drops[i]*fontSize;+ if(GLOW){ctx.shadowColor='#5fd88a';ctx.shadowBlur=8;}else{ctx.shadowBlur=0;}+ ctx.fillStyle='#d8ffe6';ctx.fillText(pick(),x,y); // bright leader+ ctx.shadowBlur=0;+ ctx.fillStyle='#3aa564';ctx.fillText(pick(),x,y-fontSize); // dimmer follower+ if(y>H&&Math.random()>.975)drops[i]=Math.floor(Math.random()*-20);+ drops[i]++;+ }+ unseen=false;+ }-function loop(ts){- if(paused){raf=null;return;}- raf=requestAnimationFrame(loop);- const dt=ts-lastT;- const f=Math.round(1000/(dt||16));fpsEl.textContent=f+' fps';fps2.textContent=f;- // Advance the rain at a rate independent of the display's refresh rate.- acc+=dt;const interval=1000/(SPD*3.5);- if(acc>=interval){acc=acc%interval;lastT=ts;step();}- else lastT=ts;-}+ // A settled picture of rain. The canvas and the columns are dealt afresh first, so no trace of an earlier picture+ // stays, then one and a half screens' worth of steps run: every column has entered view and most show a bright+ // leader with its trail behind it.+ function paintStatic(){+ deal();+ const n=Math.ceil(1.5*H/fontSize);+ for(let i=0;i<n;i++)step();+ }+ function restart(){resize();paintStatic();}-function start(){- resize();- if(reduced){paintStatic();fpsEl.textContent='static';fps2.textContent='—';return;}- lastT=performance.now();raf=requestAnimationFrame(loop);-}+ // loop() keeps exactly one frame requested in raf; Pause cancels it and Play starts one loop again. The rain takes a+ // step each time the interval has passed (three times as long in slow motion); after a pause, at most one step.+ function loop(ts){+ raf=requestAnimationFrame(loop);+ acc+=last===null?0:ts-last;last=ts;+ const interval=1000/(SPD*3.5)*(slowTog.checked?3:1);+ if(acc>=interval){acc%=interval;step();}+ }+ function start(){if(raf)return;last=null;raf=requestAnimationFrame(loop);}-let rzT;-// Debounced refit. Repaint one frame when the loop is not running, otherwise-// resize() leaves the canvas cleared to black until playback resumes.-function refit(){clearTimeout(rzT);rzT=setTimeout(()=>{resize();if(reduced||paused)paintStatic();},150);}-window.addEventListener('resize',refit);-if('ResizeObserver'in window)new ResizeObserver(refit).observe(stage);+ // 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 rain on screen stays as it is while paused, unless a setting+ // changed just before and no step has drawn it yet.+ document.addEventListener('hb:pause',e=>{+ paused=e.detail.paused;+ if(paused){cancelAnimationFrame(raf);raf=null;if(unseen)paintStatic();}+ else start();+ });+ document.addEventListener('visibilitychange',()=>{+ if(document.hidden){cancelAnimationFrame(raf);raf=null;}+ else if(!paused)start();+ });-document.addEventListener('visibilitychange',()=>{- if(reduced)return;- if(document.hidden){if(raf)cancelAnimationFrame(raf);raf=null;}- else if(!paused&&!raf){lastT=performance.now();raf=requestAnimationFrame(loop);}-});+ // Setting the canvas size wipes it, so a real change of the stage's size starts the rain over with a settled picture,+ // playing or paused. The observer reports once as soon as it starts watching, and a phone's address bar sliding in or+ // out fires resize: with the stage as it was, nothing happens.+ let rzT;+ function refit(){+ if(stage.clientWidth===W&&stage.clientHeight===H)return;+ clearTimeout(rzT);+ rzT=setTimeout(()=>{if(stage.clientWidth!==W||stage.clientHeight!==H)restart();},150);+ }-document.getElementById('spd-sl').addEventListener('input',e=>{SPD=+e.target.value;document.getElementById('spd-v').textContent=SPD;});-document.getElementById('fs-sl').addEventListener('input',e=>{fontSize=+e.target.value;document.getElementById('fs-v').textContent=fontSize;resize();if(reduced||paused)paintStatic();});-document.getElementById('fade-sl').addEventListener('input',e=>{FADE=e.target.value/100;document.getElementById('fade-v').textContent=FADE.toFixed(2).replace('0.','.');});-document.getElementById('set-sel').addEventListener('change',e=>{SET=e.target.value;});-document.getElementById('glow-tog').addEventListener('change',e=>{GLOW=e.target.checked;});-document.getElementById('pause-btn').addEventListener('click',()=>{- if(reduced)return;- paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';- if(!paused&&!raf){lastT=performance.now();raf=requestAnimationFrame(loop);}-});+ 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);+ }));+ }+ // Playing, the next steps show a changed setting. Paused, the trails need steps to show it, so a settled picture is+ // drawn; if Pause comes before any step has, the picture is drawn then. Speed changes no picture: it shows once it plays.+ function changed(){if(paused)paintStatic();else unseen=true;}+ choices('speed-seg',d=>{SPD=+d.spd;});+ choices('set-seg',d=>{SET=d.set;changed();});+ choices('fade-seg',d=>{FADE=+d.fade;changed();});+ choices('size-seg',d=>{fontSize=+d.px;restart();});+ document.getElementById('glow-tog').addEventListener('change',e=>{GLOW=e.target.checked;changed();});-start();+ restart();+ window.addEventListener('resize',refit);+ if('ResizeObserver'in window)new ResizeObserver(refit).observe(stage);+ start();+ // A window that crosses the phone size changes how far apart the columns are, even when the stage keeps its size+ function onPhone(){if(colsFor(W)!==cols)restart();}+ if(phone.addEventListener)phone.addEventListener('change',onPhone);+ else if(phone.addListener)phone.addListener(onPhone);</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 0180c881..05fea1ca 100644--- a/index.html+++ b/index.html@@ -1048,7 +1048,7 @@ const CATS=[['particle-constellation','Particle Constellation','Drifting dots link up with lines whenever they come close. Best for tech sites.'],['flow-field','Flow Field','Particles ride invisible currents, leaving fading trails. Best for art pages.'],['synthwave-grid','Synthwave Grid','A glowing grid rolls toward you under a striped sun. Best for music and games.'],- ['matrix-rain','Matrix Rain','Columns of glowing characters fall down a dark canvas, leaders bright and trails fading.'],+ ['matrix-rain','Matrix Rain','Columns of glowing characters rain down a dark screen. Best for tech themes.'],['plasma','Plasma Field','Summed sine functions of x, y, and time make a flowing, organic color field — the demoscene classic.'],]}