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 Starfield / Space Particles to the guided-steps page
matinca8262dcf8fa
diff --git a/animations/07-ambient-background/starfield/README.md b/animations/07-ambient-background/starfield/README.mdindex b14f91c7..f656b079 100644--- a/animations/07-ambient-background/starfield/README.md+++ b/animations/07-ambient-background/starfield/README.md@@ -1,7 +1,7 @@# Starfield / Space Particles## What it is-A starfield renders many small white points on a dark canvas that drift outward from a central focal point — the "flying through space" illusion. The depth effect comes from coupling a star's apparent size and speed to its distance from center: stars close to the center are small and slow; stars near the edge are larger and fast, simulating perspective acceleration. The side-scrolling variant produces the slower "looking out a spacecraft window" effect where stars at different depths move at different speeds.+A starfield fills a dark background with small stars that stream out from the center, like the view from a spaceship flying through space. Each star's size, brightness and speed depend on how far it is from the middle: near the center stars are small, dim and slow, and they grow, brighten and speed up toward the edge, which is what makes it feel deep. A sideways version drifts stars past, the nearer ones faster, like the view from a window.## When to use it- Space, astronomy, or sci-fi themed applications@@ -64,13 +64,16 @@ class DriftStar {## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|-| Star count | 300 | 100 = sparse; 300 = balanced; 800 = dense (approaching FPS limit) |-| Base speed | 0.4 | Keep it slow for ambient — fast starfields feel like hyperspace, not ambiance |-| Twinkling | On | Sinusoidal opacity variation per star; adds life without changing position |-| Acceleration factor | 2× | How much faster stars travel at the edge vs center; higher = more dramatic zoom |+| Direction | Outward | Outward streams the stars from the center; sideways drifts them past, the nearer ones faster |+| Speed | Normal | How fast the stars move: slow is 0.25, normal 0.4 and fast 0.65 pixels a frame near the center, faster toward the edge; keep it slow for a calm background |+| Number of stars | Medium | Few is 150, medium 300 and many 600; phones show at most 300 |+| Star color | White | White, a warm white, or a different pale color for each star |+| Twinkling | on | Each star gently brightens and dims on its own rhythm |+| Nebula haze | off | A faint purple and blue haze behind the stars adds depth |## Production notes- **Canvas vs DOM**: DOM elements at star counts above 50 cause heavy layout recalculation. Canvas is the right tool for this effect.+- **Phones**: the demo draws at most 300 stars on screens narrower than 600px; each star is a separate fill, so the count is the main cost.- **`ctx.fillStyle` caching**: setting `fillStyle` per star is expensive. Group stars by opacity bucket and set fillStyle once per bucket (color batching) to reduce canvas state changes.- **`requestAnimationFrame` throttling**: on 120Hz displays, the loop runs twice as fast. Cap time delta to avoid stars moving at different speeds across devices.- **Nebula background pairing**: adding a subtle radial gradient (deep purple in one quadrant, deep blue in another) behind the stars dramatically increases realism with minimal performance cost.@@ -78,6 +81,6 @@ class DriftStar {- **`prefers-reduced-motion`**: keep stars static (no animation loop) or limit to a very slow drift at 10% of normal speed.## See also-- [Aurora](../aurora/) — the atmospheric companion to a starfield sky-- [Canvas Particle Effect](../../06-3d-advanced/canvas-particle-effect/) — physics-based particles with connections-- [Floating Elements](../floating-elements/) — geometric shapes drifting with sine-wave motion+- [Aurora / Northern Lights](../aurora/) — bands of light that pair with a night sky+- [Canvas Particle Effect](../../06-3d-advanced/canvas-particle-effect/) — particles that link up and react to the pointer+- [Floating Elements](../floating-elements/) — shapes that drift slowly on their own pathsdiff --git a/animations/07-ambient-background/starfield/index.html b/animations/07-ambient-background/starfield/index.htmlindex d45b317d..9037dd3e 100644--- a/animations/07-ambient-background/starfield/index.html+++ b/animations/07-ambient-background/starfield/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Starfield / Space Particles — Animation Handbook</title>- <meta name="description" content="Stars drift outward from center with parallax depth — slower near center, faster at edges.">+ <meta name="description" content="Stars stream toward you out of the dark. Best for space themes."><link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/starfield/"><link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png"><link rel="icon" type="image/svg+xml" href="../../../favicon.svg">@@ -12,207 +12,288 @@<meta property="og:type" content="article"><meta property="og:site_name" content="Animation Handbook"><meta property="og:title" content="Starfield / Space Particles — Animation Handbook">- <meta property="og:description" content="Stars drift outward from center with parallax depth — slower near center, faster at edges.">+ <meta property="og:description" content="Stars stream toward you out of the dark. Best for space themes."><meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/starfield/"><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="Starfield / Space Particles — Animation Handbook">- <meta name="twitter:description" content="Stars drift outward from center with parallax depth — slower near center, faster at edges.">+ <meta name="twitter:description" content="Stars stream toward you out of the dark. Best for space 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": "Starfield / Space Particles", "name": "Starfield / Space Particles", "description": "Stars drift outward from center with parallax depth — slower near center, faster at edges.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/starfield/", "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, Starfield / Space Particles"}</script>+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Starfield / Space Particles", "name": "Starfield / Space Particles", "description": "Stars stream toward you out of the dark. Best for space themes.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/07-ambient-background/starfield/", "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, Starfield / Space Particles"}</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}+ :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{flex:1;min-width:0;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}.fg-card{position:absolute;bottom:28px;left:50%;transform:translateX(-50%);width:clamp(180px,55%,280px);background:rgba(0,0,0,.65);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:16px 18px;z-index:10;text-align:center}- .fg-eyebrow{font-size:9px;letter-spacing:2px;text-transform:uppercase;color:rgba(255,255,255,.4);margin-bottom:6px}- .fg-title{font-family:Georgia,serif;font-size:clamp(13px,1.8vw,17px);color:#fff;margin-bottom:6px;font-style:italic}- .fg-body{font-size:10px;color:rgba(255,255,255,.4);line-height:1.6}- 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}.stage{flex:none;width:100%}aside{width:100%}:root{--stage-h:380px}}+ .fg-eyebrow{font-size:11px;font-weight:600;letter-spacing:2px;text-transform:uppercase;color:rgba(255,255,255,.6);margin-bottom:6px}+ .fg-title{font-size:clamp(13px,1.8vw,17px);font-weight:700;color:#fff;margin-bottom:6px}+ .fg-body{font-size:13px;color:rgba(255,255,255,.72);line-height:1.6}+ /* On phones and short screens the stage is small, so the card shrinks to leave the stars in view */+ @media(max-width:600px),(max-height:760px){+ .fg-card{padding:12px 14px}+ .fg-eyebrow{margin-bottom:4px}+ .fg-title{margin-bottom:0}+ .fg-body{display:none}+ }</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="../light-leak/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../breathing-glow/" 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/starfield/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>-<header>- <h1>Starfield / Space Particles</h1>- <p>Stars drift outward from center with parallax depth — slower near center, faster at edges.</p>-</header>-<div class="layout">- <div class="stage" id="stage">- <canvas id="cvs"></canvas>- <div class="fps-badge" id="fps">— fps</div>- <div class="fg-card">- <div class="fg-eyebrow">Starfield</div>- <div class="fg-title">Infinite depth from a single point</div>- <div class="fg-body">Stars start small at center, grow as they reach the edge — perspective through motion.</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="../light-leak/" rel="prev" aria-label="Previous: Light Leak"><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>Light Leak</span></a><a href="../breathing-glow/" rel="next" aria-label="Next: Breathing / Pulsing Glow"><span><span class="hb-dir">Next: </span>Breathing / Pulsing Glow</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.07 · Ambient & Background</p>+ <h1>Starfield / Space Particles</h1>+ <p class="hb-lede">Stars stream toward you out of the dark. Best for space 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">Depth illusion: couple size and speed to distance from center. Stars near center = slow, tiny. Stars at edge = fast, large. This single trick creates convincing 3D perspective.</p>- <div class="lbl">Mode</div>- <select id="mode-sel">- <option value="radial" selected>Radial (outward)</option>- <option value="drift">Side drift (parallax)</option>- </select>- <div class="lbl">Star Count</div>- <div class="sr"><input type="range" id="count-sl" min="50" max="800" value="300" step="50"><span class="sv" id="count-v">300</span></div>- <div class="lbl">Speed</div>- <div class="sr"><input type="range" id="spd-sl" min="1" max="20" value="4" step="1"><span class="sv" id="spd-v">0.4</span></div>- <div class="lbl">Star Color</div>- <select id="col-sel">- <option value="white" selected>White</option>- <option value="warm">Warm white</option>- <option value="color">Multi-color</option>- </select>- <label class="tog"><input type="checkbox" id="twinkle-tog" checked><span>Twinkling</span></label>- <label class="tog"><input type="checkbox" id="nebula-tog"><span>Nebula haze</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');-let W,H,paused=false,raf=null,lastT=0,MODE='radial',COUNT=300,SPD=0.4,TWINKLE=true,NEBULA=false,COL='white';-let stars=[];-const REDUCED=matchMedia('(prefers-reduced-motion:reduce)').matches;+ <div class="stage">+ <canvas id="cvs" aria-hidden="true"></canvas>+ <div class="fg-card">+ <div class="fg-eyebrow">Starfield</div>+ <div class="fg-title">Infinite depth from a single point</div>+ <div class="fg-body">Small, slow stars in the middle grow and speed up toward the edge.</div>+ </div>+ </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>++ <section class="hb-step hb-try" aria-labelledby="hb-try-title">+ <div class="hb-step-head">+ <span class="hb-num" aria-hidden="true">2</span>+ <div><h2 id="hb-try-title">Try it</h2><p>Change a setting and see the difference as it moves.</p></div>+ </div>+ <div class="hb-settings">+ <div class="hb-setting">+ <p class="hb-setting-name" id="dir-lbl">Direction</p>+ <div class="seg" id="dir-seg" role="group" aria-labelledby="dir-lbl">+ <button type="button" data-mode="radial" class="on" aria-pressed="true">Outward</button>+ <button type="button" data-mode="drift" aria-pressed="false">Sideways</button>+ </div>+ <p class="hb-hint">Outward flies through space; sideways looks out a window.</p>+ </div>+ <div class="hb-setting">+ <p class="hb-setting-name" id="speed-lbl">Speed</p>+ <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">+ <button type="button" data-spd="0.25" aria-pressed="false">Slow</button>+ <button type="button" data-spd="0.4" class="on" aria-pressed="true">Normal</button>+ <button type="button" data-spd="0.65" aria-pressed="false">Fast</button>+ </div>+ <p class="hb-hint">Keep it slow for a calm background.</p>+ </div>+ <div class="hb-setting">+ <p class="hb-setting-name" id="count-lbl">Number of stars</p>+ <div class="seg" id="count-seg" role="group" aria-labelledby="count-lbl">+ <button type="button" data-n="150" aria-pressed="false">Few</button>+ <button type="button" data-n="300" class="on" aria-pressed="true">Medium</button>+ <button type="button" data-n="600" aria-pressed="false">Many</button>+ </div>+ <p class="hb-hint">More stars feel deeper; phones show at most 300.</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="col-lbl">Star color</p>+ <div class="seg" id="col-seg" role="group" aria-labelledby="col-lbl">+ <button type="button" data-col="white" class="on" aria-pressed="true">White</button>+ <button type="button" data-col="warm" aria-pressed="false">Warm white</button>+ <button type="button" data-col="color" aria-pressed="false">Many colors</button>+ </div>+ <p class="hb-hint">The color of the stars.</p>+ </div>+ <div class="hb-setting">+ <label class="hb-switch-row"><span>Twinkling</span><input class="hb-switch" type="checkbox" role="switch" id="twinkle-tog" checked autocomplete="off"></label>+ <p class="hb-hint">Each star gently brightens and dims.</p>+ </div>+ <div class="hb-setting">+ <label class="hb-switch-row"><span>Nebula haze</span><input class="hb-switch" type="checkbox" role="switch" id="nebula-tog" autocomplete="off"></label>+ <p class="hb-hint">A faint purple and blue haze behind the stars.</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 starfield background to [the dark section you want it behind]. Draw many small stars on a canvas and move them out from the center, or sideways past the viewer, so it feels like flying through space. Tie each star's size, brightness and speed to its distance from the center: small, dim and slow near the middle, bigger, brighter and faster toward the edge, which is what creates the depth. A slow speed keeps it calm. Draw fewer stars on phones. If the visitor has reduced motion turned on, show the stars 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>Space and science themes</li><li>Hero sections</li><li>Screensavers and kiosks</li><li>Launch pages</li></ul>+ <h3>Avoid on</h3>+ <ul class="hb-tags hb-avoid"><li>Light pages</li><li>Long reading pages</li></ul>+ </div>+ </section>-function resize(){- const dpr=Math.min(window.devicePixelRatio||1,2);- W=stage.clientWidth;H=stage.clientHeight;- cvs.width=W*dpr;cvs.height=H*dpr;ctx.setTransform(dpr,0,0,dpr,0,0);- initStars();-}+ <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 PHONE_STARS=300; // a stage narrower than 600px draws at most this many stars+ let W=0,H=0,raf=null,lastT=0,paused=false;+ let MODE='radial',COUNT=300,SPD=0.4,TWINKLE=true,NEBULA=false,COL='white';+ let stars=[];-class Star{- constructor(init){- if(MODE==='radial'){- this.angle=Math.random()*Math.PI*2;- this.dist=init?Math.random()*Math.max(W,H)*.5:0;- this.maxDist=Math.max(W,H)*.55;- this.speed=(Math.random()*.6+.2)*SPD;- this.size=Math.random()*1.5+.5;- this.twinklePhase=Math.random()*Math.PI*2;- }else{- this.x=Math.random()*W;this.y=Math.random()*H;- this.depth=Math.random()*.8+.2;- this.size=(Math.random()*1.5+.5)*this.depth;- this.twinklePhase=Math.random()*Math.PI*2;+ class Star{+ constructor(init){+ if(MODE==='radial'){+ this.angle=Math.random()*Math.PI*2;+ this.dist=init?Math.random()*Math.max(W,H)*.5:0;+ this.maxDist=Math.max(W,H)*.55;+ this.speed=(Math.random()*.6+.2)*SPD;+ this.size=Math.random()*1.5+.5;+ this.twinklePhase=Math.random()*Math.PI*2;+ }else{+ this.x=Math.random()*W;this.y=Math.random()*H;+ this.depth=Math.random()*.8+.2;+ this.size=(Math.random()*1.5+.5)*this.depth;+ this.twinklePhase=Math.random()*Math.PI*2;+ }+ this.hue=Math.random()*60;}- this.hue=Math.random()*60;- }- update(){- if(MODE==='radial'){- this.dist+=this.speed;- const ratio=this.dist/this.maxDist;- this.speed=(ratio*.5+.2)*SPD*1.5;- if(this.dist>this.maxDist){this.dist=0;this.speed=(Math.random()*.6+.2)*SPD;this.angle=Math.random()*Math.PI*2;}- }else{- this.x-=this.depth*SPD*2;if(this.x<-2){this.x=W+2;}+ // k is 1, or a third in slow motion: the outward step, the sideways step and the twinkle all shrink by it+ update(k){+ if(MODE==='radial'){+ this.dist+=this.speed*k;+ const ratio=this.dist/this.maxDist;+ this.speed=(ratio*.5+.2)*SPD*1.5;+ if(this.dist>this.maxDist){this.dist=0;this.speed=(Math.random()*.6+.2)*SPD;this.angle=Math.random()*Math.PI*2;}+ }else{+ this.x-=this.depth*SPD*2*k;if(this.x<-2){this.x=W+2;}+ }+ this.twinklePhase+=.05*k;}- this.twinklePhase+=.05;- }- draw(){- const ratio=MODE==='radial'?this.dist/this.maxDist:this.depth;- let col='rgba(255,255,255,';- if(COL==='warm')col=`rgba(255,240,200,`;- if(COL==='color')col=`hsla(${this.hue},80%,90%,`;- const sz=this.size*(1+ratio*1.5);- const twinkle=TWINKLE?(.7+Math.sin(this.twinklePhase)*.3):1;- const op=(ratio*.7+.3)*twinkle;- ctx.fillStyle=col+op+')';- ctx.beginPath();- if(MODE==='radial'){- const x=W/2+Math.cos(this.angle)*this.dist,y=H/2+Math.sin(this.angle)*this.dist;- ctx.arc(x,y,sz,0,Math.PI*2);- }else{- ctx.arc(this.x,this.y,sz,0,Math.PI*2);+ draw(){+ const ratio=MODE==='radial'?this.dist/this.maxDist:this.depth;+ let col='rgba(255,255,255,';+ if(COL==='warm')col=`rgba(255,240,200,`;+ if(COL==='color')col=`hsla(${this.hue},80%,90%,`;+ const sz=this.size*(1+ratio*1.5);+ const twinkle=TWINKLE?(.7+Math.sin(this.twinklePhase)*.3):1;+ const op=(ratio*.7+.3)*twinkle;+ ctx.fillStyle=col+op+')';+ ctx.beginPath();+ if(MODE==='radial'){+ const x=W/2+Math.cos(this.angle)*this.dist,y=H/2+Math.sin(this.angle)*this.dist;+ ctx.arc(x,y,sz,0,Math.PI*2);+ }else{+ ctx.arc(this.x,this.y,sz,0,Math.PI*2);+ }+ ctx.fill();}- ctx.fill();}-}-function initStars(){stars=Array.from({length:COUNT},(_,i)=>new Star(true));redraw();}+ function initStars(){+ const n=W<600?Math.min(COUNT,PHONE_STARS):COUNT;+ stars=Array.from({length:n},()=>new Star(true));+ }++ function drawNebula(){+ const g=ctx.createRadialGradient(W*.3,H*.4,0,W*.3,H*.4,W*.5);+ g.addColorStop(0,'rgba(50,20,100,.15)');g.addColorStop(1,'transparent');+ ctx.fillStyle=g;ctx.fillRect(0,0,W,H);+ const g2=ctx.createRadialGradient(W*.7,H*.6,0,W*.7,H*.6,W*.4);+ g2.addColorStop(0,'rgba(20,50,80,.1)');g2.addColorStop(1,'transparent');+ ctx.fillStyle=g2;ctx.fillRect(0,0,W,H);+ }-function drawNebula(){- const g=ctx.createRadialGradient(W*.3,H*.4,0,W*.3,H*.4,W*.5);- g.addColorStop(0,'rgba(50,20,100,.15)');g.addColorStop(1,'transparent');- ctx.fillStyle=g;ctx.fillRect(0,0,W,H);- const g2=ctx.createRadialGradient(W*.7,H*.6,0,W*.7,H*.6,W*.4);- g2.addColorStop(0,'rgba(20,50,80,.1)');g2.addColorStop(1,'transparent');- ctx.fillStyle=g2;ctx.fillRect(0,0,W,H);-}+ // One picture. paint(true) is a frame of the loop: a see-through cover leaves short trails, then the stars move and+ // are drawn. paint(false) draws the picture where it stands, for the first frame, after a resize and after a setting+ // changes while paused; nothing moved, so it covers the old picture completely.+ function paint(move){+ ctx.fillStyle=move?'rgba(0,0,0,.85)':'#000';ctx.fillRect(0,0,W,H);+ if(NEBULA)drawNebula();+ const k=slowTog.checked?1/3:1;+ stars.forEach(s=>{if(move)s.update(k);s.draw();});+ }+ // While paused, a setting that changes the picture draws it again so the change shows+ function still(){if(paused)paint(false);}-function loop(ts){- if(paused){raf=null;return;}- if(REDUCED){raf=null;}- else{+ // loop() keeps exactly one frame requested in raf; Pause cancels it and Play starts one loop again.+ function loop(ts){raf=requestAnimationFrame(loop);- const dt=ts-lastT;if(dt<16)return;- const f=Math.round(1000/(dt||16));fpsEl.textContent=f+' fps';fps2.textContent=f;lastT=ts;+ if(ts-lastT<16)return;+ lastT=ts;+ paint(true);}- ctx.fillStyle=REDUCED?'#000':'rgba(0,0,0,.85)';ctx.fillRect(0,0,W,H);- if(NEBULA)drawNebula();- stars.forEach(s=>{if(!REDUCED)s.update();s.draw();});-}+ function start(){if(raf)return;lastT=0;raf=requestAnimationFrame(loop);}-// reduced motion draws one static frame, so control changes have to ask for a repaint-function redraw(){if(REDUCED&&!paused&&raf===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 stars on screen stay as they are while paused.+ document.addEventListener('hb:pause',e=>{+ paused=e.detail.paused;+ if(paused){cancelAnimationFrame(raf);raf=null;}+ else start();+ });-resize();-if(REDUCED){fpsEl.textContent='static';fps2.textContent='static';}-raf=requestAnimationFrame(loop);-window.addEventListener('resize',resize);+ // Setting the canvas size wipes it, so a real change of the stage's size builds the stars and draws them 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=w;H=h;+ const dpr=Math.min(window.devicePixelRatio||1,2);+ cvs.width=W*dpr;cvs.height=H*dpr;ctx.setTransform(dpr,0,0,dpr,0,0);+ initStars();paint(false);+ }++ 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);+ }));+ }+ choices('dir-seg',d=>{MODE=d.mode;initStars();still();});+ choices('speed-seg',d=>{SPD=+d.spd;});+ choices('count-seg',d=>{COUNT=+d.n;initStars();still();});+ choices('col-seg',d=>{COL=d.col;still();});+ document.getElementById('twinkle-tog').addEventListener('change',e=>{TWINKLE=e.target.checked;still();});+ document.getElementById('nebula-tog').addEventListener('change',e=>{NEBULA=e.target.checked;still();});-document.getElementById('mode-sel').addEventListener('change',e=>{MODE=e.target.value;initStars();});-document.getElementById('count-sl').addEventListener('input',e=>{COUNT=+e.target.value;document.getElementById('count-v').textContent=COUNT;initStars();});-document.getElementById('spd-sl').addEventListener('input',e=>{SPD=e.target.value/10;document.getElementById('spd-v').textContent=SPD.toFixed(1);redraw();});-document.getElementById('col-sel').addEventListener('change',e=>{COL=e.target.value;redraw();});-document.getElementById('twinkle-tog').addEventListener('change',e=>{TWINKLE=e.target.checked;redraw();});-document.getElementById('nebula-tog').addEventListener('change',e=>{NEBULA=e.target.checked;redraw();});-document.getElementById('pause-btn').addEventListener('click',()=>{- paused=!paused;document.getElementById('pause-btn').textContent=paused?'▶ Resume':'⏸ Pause';- if(!paused){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 c5bb93ba..f0cf222f 100644--- a/index.html+++ b/index.html@@ -1039,7 +1039,7 @@ const CATS=[['grain-overlay','Grain / Film Noise Overlay','Fine grain flickers over the page, like old film. Best for editorial sites.'],['scanline','Scanline Effect','Dark lines and a sweeping beam imitate an old TV screen. Best for retro sites.'],['light-leak','Light Leak','Warm light washes in from a corner at random times. Best for photo sites.'],- ['starfield','Starfield / Space Particles','Stars drift outward from center with parallax depth — slow ambient speed, never hyperspace.'],+ ['starfield','Starfield / Space Particles','Stars stream toward you out of the dark. Best for space themes.'],['breathing-glow','Breathing / Pulsing Glow','Radial glow expands and contracts on a 5-second breath cycle — calm resting state.'],['ambient-ripple','Ambient Ripple Effect','Concentric rings emit periodically from idle sources — passive atmosphere, not click-driven.'],['floating-elements','Floating Elements','Geometric shapes drift on independent sine-wave paths — no two elements synchronized.'],