176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Matrix Rain — Animation Handbook</title>
<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">
<link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="Matrix Rain — Animation Handbook">
<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 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 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>
:root{--ui-accent:#ffce5a}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
.stage{position:relative;overflow:hidden;background:#000}
canvas{display:block;width:100%;height:100%}
/* See inside: a canvas of marks over the rain and three captions at the top left. Compare: a name at the top of each half */
.mr-keys,.mr-half{border:1px solid rgba(255,255,255,.14);background:rgba(0,0,0,.88);color:#f4f4f2;font:600 13px/1.2 var(--hb-font);white-space:nowrap}
.mr-keys{position:absolute;left:10px;top:10px;flex-direction:column;align-items:flex-start;gap:6px;padding:7px 11px;border-radius:10px}
.mr-cap svg{display:inline-block;width:12px;height:12px;margin-right:7px;vertical-align:-1px;fill:none;stroke:#fff;stroke-width:1.6}
.mr-cap.gold svg{stroke:#ffce5a;stroke-width:2.2}
.mr-ov{position:absolute;inset:0;pointer-events:none}
.mr-half{position:absolute;top:10px;left:10px;padding:4px 10px;border-radius:999px}
.mr-half.two{margin-left:10px} /* its left edge, the divider, is set by the script */
.mr-ov,.mr-keys,.mr-half{display:none}
.stage[data-hb-mode="inside"] .mr-ov{display:block}
.stage[data-hb-mode="inside"] .mr-keys{display:flex}
.stage[data-hb-mode="compare"] .mr-half{display:block}
@media(max-width:600px){.mr-keys{left:6px;top:6px;gap:5px;padding:5px 8px}.mr-keys,.mr-half{font-size:12px}.mr-half{top:6px;left:6px;padding:2px 7px}.mr-half.two{margin-left:6px}}
</style>
<link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
<script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="loop">
<nav class="hb-bar" aria-label="Animation Handbook">
<a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
<span class="hb-pager"><a href="../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>
<a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
<header class="hb-head">
<p class="hb-cat">07.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 class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
<button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
<button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
<button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
</div>
<div class="stage">
<canvas id="cvs" aria-hidden="true"></canvas>
<canvas class="mr-ov" id="marks" aria-hidden="true"></canvas>
<div class="mr-keys" aria-hidden="true">
<p class="mr-cap" data-hb-caption><svg viewBox="0 0 12 12"><rect x="1" y="1" width="10" height="10"/></svg>One leader per column, <span class="mr-rate">28</span> rows a second</p>
<p class="mr-cap gold" data-hb-caption><svg viewBox="0 0 12 12"><path d="M3 1h5v10H3"/></svg>Dimmed each step, so a trail fades</p>
<p class="mr-cap" data-hb-caption><svg viewBox="0 0 12 12"><path d="M6 11.5V1.5M2.5 5 6 1.5 9.5 5"/></svg>Past the bottom, back to the top at random</p>
</div>
<p class="mr-half one" aria-hidden="true" data-hb-caption>Cleared each step</p>
<p class="mr-half two" aria-hidden="true" data-hb-caption>Dimmed each step</p>
</div>
<div class="hb-player">
<button class="hb-play" type="button" id="btn-pause" data-hb-pause data-state="playing"><svg class="hb-ic hb-i-pause" viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg><svg class="hb-ic hb-i-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3l14 9-14 9z"/></svg><span class="hb-pause-label">Pause</span></button>
<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>
</div>
<div class="hb-mode-notes" aria-live="polite">
<p data-hb-for="inside" hidden>Inside, each column has one bright leader that steps down a row at a time. The whole screen is dimmed a little each step, so older characters fade into a trail.</p>
<p data-hb-for="compare" hidden>Cleared each step wipes its half to black, so each leader shows with just one dim character above it. Dimmed each step only darkens it a little, so each leader leaves a fading trail.</p>
</div>
</section>
<section class="hb-step hb-try" aria-labelledby="hb-try-title">
<div class="hb-step-head">
<span class="hb-num" aria-hidden="true">2</span>
<div><h2 id="hb-try-title">Try it</h2><p>Change a setting and see the difference as it moves.</p></div>
</div>
<div class="hb-settings">
<div class="hb-setting">
<p class="hb-setting-name" id="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>
<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>
<div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
</section>
<section class="hb-about" aria-labelledby="hb-what-title">
<div class="hb-what">
<h2 id="hb-what-title">What it is</h2>
<div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
</div>
<div class="hb-fit">
<h2>Good for</h2>
<ul class="hb-tags hb-good"><li>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>
<section class="hb-related" aria-labelledby="hb-related-title" hidden>
<h2 id="hb-related-title">Similar animations</h2>
<div class="hb-rel-list"></div>
</section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
const cvs=document.getElementById('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;
// See inside and Compare: the marks' canvas over the rain; count numbers the steps and back holds the step at which each column
// last went back to the top; bc is the column with the gold bracket, picked at step bcAt; lg is the captions' box on the marks'
// canvas (with a margin); kept holds Normal's picture, columns and time while Compare shows
const ov=document.getElementById('marks'),octx=ov.getContext('2d');
const keep=document.createElement('canvas'),kctx=keep.getContext('2d');
const keys=stage.querySelector('.mr-keys'),rate=stage.querySelector('.mr-rate'),half2=stage.querySelector('.mr-half.two');
let mode='normal',count=0,back=[],bc=-1,bcAt=0,lg={l:0,r:0,b:0},kept=null;
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);
kept=null;half2.style.left=Math.floor(cols/2)*W/cols+'px'; // Compare's second half starts at the column edge nearest the middle
deal();
}
function pick(){const s=SETS[SET];return s[Math.floor(Math.random()*s.length)];}
// 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. In Compare the first
// half (the columns left of the edge nearest the middle) is cleared to black after the dim, and each half draws only inside itself.
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;
count++;
if(mode==='compare'){
const k=Math.floor(cols/2),sx=k*pitch;
ctx.fillStyle='#000';ctx.fillRect(0,0,sx,H);
for(const[a,b,x0,x1]of[[0,k,0,sx],[k,cols,sx,W]]){ctx.save();ctx.beginPath();ctx.rect(x0,0,x1-x0,H);ctx.clip();for(let i=a;i<b;i++)column(i,pitch);ctx.restore();}
ctx.fillStyle='#50535b';ctx.fillRect(sx-1,0,2,H); // the divider
}else for(let i=0;i<cols;i++)column(i,pitch);
unseen=false;
}
function column(i,pitch){
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);back[i]=count;}
drops[i]++;
}
// A settled picture of rain: columns dealt afresh over a whole cycle (above, on and below the screen) on a black
// canvas, then a screen of steps, so it looks like rain in full flow.
function paintStatic(){
const rows=H/fontSize;drops=Array.from({length:cols},()=>Math.floor(Math.random()*3*rows-2*rows));ctx.fillStyle='#000';ctx.fillRect(0,0,W,H);
back=drops.map(()=>-1e9);bc=-1;
const n=Math.ceil(rows);
if(mode==='compare')pose(rows,n);
for(let i=0;i<n;i++)step();
if(mode==='inside')marks();
}
// Compare's settled picture is posed: each half gets at least three leaders that end the settled steps on screen, below the names
function pose(rows,n){
const k=Math.floor(cols/2),lands=i=>drops[i]+n>=4&&drops[i]+n<=rows; // its leader ends on row 3 or lower, in full view
for(const[a,b]of[[0,k],[k,cols]]){
let have=0;for(let i=a;i<b;i++)if(lands(i))have++;
for(let t=0;have<3&&t<60;t++){const i=a+Math.floor(Math.random()*(b-a));if(!lands(i)){drops[i]=Math.floor(3+Math.random()*(rows-4))+1-n;have++;}}
}
}
// See inside, on its own canvas over the rain (nothing is drawn on the rain, which keeps its trails): a faint line at each
// column's edges, a box around every leader on screen, an up arrow at the bottom of each column that went back to the top in the
// last half second of play (counted in steps, so Pause holds it; at least the last one), and a gold bracket up the trail of one
// leader near the middle, its tick where the trail is half as bright (none where that is above the top edge or under the captions)
function marks(){
if(ov.width!==cvs.width||ov.height!==cvs.height){ov.width=cvs.width;ov.height=cvs.height;}
octx.setTransform(dpr,0,0,dpr,0,0);octx.clearRect(0,0,W,H);
const per=String(Math.round(SPD*3.5/(slowTog.checked?3:1)));if(rate.textContent!==per)rate.textContent=per; // a third in slow motion
const o=ov.getBoundingClientRect(),c=keys.getBoundingClientRect();lg={l:c.left-o.left-10,r:c.right-o.left+10,b:c.bottom-o.top+4};
const p=W/cols,fs=fontSize,hr=Math.log(.5)/Math.log(1-FADE),on=i=>drops[i]>0&&(drops[i]-1)*fs<H;
octx.lineWidth=1;octx.strokeStyle='rgba(255,255,255,.2)';octx.beginPath();
for(let i=1;i<cols;i++){const x=Math.round(i*p)+.5;octx.moveTo(x,0);octx.lineTo(x,H);}
octx.stroke();
octx.lineWidth=1.5;octx.strokeStyle='#fff';octx.beginPath();
for(let i=0;i<cols;i++)if(on(i))octx.rect(i*p+1,(drops[i]-1)*fs+1,p-2,fs-2);
octx.stroke();
let la=-1; // the column that went back last; before any has, the one longest past the bottom
for(let i=0;i<cols;i++)if(back[i]>-1e9&&(la<0||back[i]>back[la]))la=i;
if(la<0)for(let i=0;i<cols;i++)if((drops[i]-1)*fs>H&&(la<0||drops[i]>drops[la]))la=i;
const up=new Path2D();
for(let i=0;i<cols;i++)if(i===la||count-back[i]<SPD*1.75){const x=(i+.5)*p;up.moveTo(x,H-3);up.lineTo(x,H-17);up.moveTo(x-4,H-13);up.lineTo(x,H-17);up.lineTo(x+4,H-13);}
ink(up,'#fff',2);
// The bracket keeps its column until the column goes back to the top or the tick passes the bottom: once the leader has left,
// it runs from the bottom edge up to the tick, which falls with the trail
if(bc<0||back[bc]>=bcAt||(drops[bc]-hr)*fs>=H)bc=bracketCol(hr);
if(bc>=0){
const x=(bc+1)*p+2.5,yb=drops[bc]*fs,yt=yb-hr*fs,tick=shows(x,yt),y0=tick?yt:under(x)?lg.b:0,br=new Path2D();
if(y0<Math.min(yb,H)-4){
if(yb<=H){br.moveTo(x-5,yb);br.lineTo(x,yb);}else br.moveTo(x,H);
br.lineTo(x,y0);if(tick)br.lineTo(x-9,yt);
ink(br,'#ffce5a',2.5);
}
}
}
function ink(path,color,w){octx.lineCap='round';octx.lineJoin='round';octx.lineWidth=w+2.5;octx.strokeStyle='rgba(0,0,0,.8)';octx.stroke(path);octx.lineWidth=w;octx.strokeStyle=color;octx.stroke(path);}
function under(x){return x>lg.l&&x<lg.r;}
function shows(x,y){return y>=0&&y<H&&!(under(x)&&y<lg.b);}
// The bracket's column, of the leaders on screen near the middle (a row counts as much as about two columns). In a still: the
// lowest whose tick shows (the most trail in view), else the lowest. In play: the highest clear of the captions, for the longest
// ride (its bracket grows up to the captions or the top edge until the tick comes into view)
function bracketCol(hr){
const p=W/cols,fs=fontSize,rows=H/fs;
let best=-1,top=-Infinity;
for(let i=0;i<cols-1;i++){
const L=drops[i]-1;if(L<0||L>=rows)continue;
const x=(i+1)*p+2.5,d=Math.abs(x-W/2),s=paused?(shows(x,(L+1-hr)*fs)?1e6+L*fs-d/2:L*1e3-d)
:(!under(x)||L*fs>=lg.b?1e6+(rows-L)*fs-d/2:L*1e3-d);
if(s>top){top=s;best=i;}
}
bcAt=count;return best;
}
function restart(){resize();paintStatic();}
// 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();if(mode==='inside')marks();}
}
function start(){if(raf)return;last=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 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();
});
// The mode switch draws the mode at once, playing or paused. Compare keeps Normal's picture, columns and time (unless a changed
// setting is not drawn yet) and draws a settled picture of its two halves; leaving it puts Normal's back, or draws a settled
// picture after a setting or size change. See inside draws its marks over the rain as it is.
document.addEventListener('hb:mode',e=>{
const was=mode;mode=e.detail.mode;
if(mode==='compare'&&was!=='compare'){
kept=unseen?null:{drops:drops.slice(),back:back.slice(),count,acc};
if(kept){keep.width=cvs.width;keep.height=cvs.height;kctx.drawImage(cvs,0,0);}
paintStatic();
}else if(was==='compare'&&mode!=='compare'){
if(kept&&keep.width===cvs.width&&keep.height===cvs.height&&kept.drops.length===cols){
ctx.save();ctx.setTransform(1,0,0,1,0,0);ctx.drawImage(keep,0,0);ctx.restore();
({drops,back,count,acc}=kept);
}else paintStatic();
kept=null;
}
if(mode==='inside'){if(was!=='inside')bc=-1;marks();}else octx.clearRect(0,0,W,H);
});
// 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);
}
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
// (and at once in See inside's caption, as Slow motion does). A changed setting also drops a kept Normal picture.
function changed(){kept=null;if(paused)paintStatic();else unseen=true;}
choices('speed-seg',d=>{SPD=+d.spd;if(mode==='inside')marks();});
slowTog.addEventListener('change',()=>{if(mode==='inside')marks();});
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();});
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>
</body>
</html>