Riff Shades
Emerald dust on a dark disc and four switches. Three of them play piano chords and the dust jumps into a new figure on every hit. The fourth drops the beat and the dust builds pixel shades that nod to the tempo.
- Particles & fun
- Free
- canvas
- particles
- sound
- Added Oct 17, 2026
<style>
/* Riff Shades by @codinvisual · t.me/CodinVisual · page shell, only needed while this file is the whole page */
</style>
<!-- riff start -->
<div class="rs">
<canvas class="rs-grain" aria-hidden="true"></canvas>
<div class="rs-stage" aria-hidden="true"><canvas class="rs-floor"></canvas><canvas class="rs-dust"></canvas></div>
<div class="rs-box">
<button class="rs-sw" type="button" aria-label="First chord"><span class="rs-led"><i></i></span><span class="rs-nut"></span><span class="rs-lever"></span><span class="rs-tip"></span><span class="rs-key">A</span></button>
<button class="rs-sw" type="button" aria-label="Second chord"><span class="rs-led"><i></i></span><span class="rs-nut"></span><span class="rs-lever"></span><span class="rs-tip"></span><span class="rs-key">S</span></button>
<button class="rs-sw" type="button" aria-label="Third chord"><span class="rs-led"><i></i></span><span class="rs-nut"></span><span class="rs-lever"></span><span class="rs-tip"></span><span class="rs-key">D</span></button>
<button class="rs-sw" type="button" aria-label="Drop the shades"><span class="rs-led"><i></i></span><span class="rs-nut"></span><span class="rs-lever"></span><span class="rs-tip"></span><span class="rs-key"><svg viewBox="0 0 12 5" width="17" height="7" aria-hidden="true" fill="currentColor"><path d="M0 0h12v1H11v2h-1v1H8V3H7V1H5v2H4v1H2V3H1V1H0z"/></svg>F</span></button>
</div>
<button class="rs-sound" type="button" aria-pressed="true"><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M4 9.5h3.5L12 5.5v13L7.5 14.5H4z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/><path d="M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg><span>Sound</span></button>
<p class="rs-hint" aria-hidden="true">Play the switches<span class="rs-keys"> · keys A S D F</span></p>
</div>
<!-- riff end -->
<script>
/* Riff Shades by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */
(() => {
const GRAINS = 9000;
const JUMP = 0.06;
const SETTLE = 0.35;
const HOP = 320;
const TEMPO = 94;
const TUNE = 50;
const CHORDS = [
[45, 72, 76, 81],
[40, 71, 76, 81],
[40, 71, 76, 79]
];
const KICK = [0, 4, 5], SNARE = [2, 6];
const SHAPES = [[4, 1.5, 0], [0, 3.5, 0], [5, .5, 2.6]];
const SHADES = [
'########################',
'..##########..##########',
'..##oo######..##oo######',
'..####oo####..####oo####',
'....######......######..'
];
const root = document.querySelector('.rs');
if (!root) return;
const stage = root.querySelector('.rs-stage'), floor = root.querySelector('.rs-floor'), dust = root.querySelector('.rs-dust');
const sw = [...root.querySelectorAll('.rs-sw')], soundBtn = root.querySelector('.rs-sound'), hint = root.querySelector('.rs-hint'), grain = root.querySelector('.rs-grain');
const lever = sw.map(b => b.querySelector('.rs-lever')), tip = sw.map(b => b.querySelector('.rs-tip')), led = sw.map(b => b.querySelector('.rs-led i'));
const calm = matchMedia('(prefers-reduced-motion: reduce)');
const ctx = dust.getContext('2d'), page = document.createElement('canvas'), pctx = page.getContext('2d');
const halo = document.createElement('canvas'), hctx = halo.getContext('2d');
const { cos, PI } = Math;
const R = .44, TOP = .2, MID = .5, E = 30 / TEMPO;
let seed = 1017;
const rnd = () => {
seed = seed + 0x6D2B79F5 | 0;
let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
// dust lives in stage units, 0 to 1 across; at first it is simply spread over the disc
const gx = new Float32Array(GRAINS), gy = new Float32Array(GRAINS), up = new Float32Array(GRAINS), rise = new Float32Array(GRAINS), tone = new Float32Array(GRAINS);
const tx = new Float32Array(GRAINS), ty = new Float32Array(GRAINS), vx = new Float32Array(GRAINS), vy = new Float32Array(GRAINS), wait = new Float32Array(GRAINS), hot = new Uint8Array(GRAINS);
for (let i = 0; i < GRAINS; i++) {
const r = R * Math.sqrt(rnd()) * .98, a = rnd() * PI * 2;
gx[i] = .5 + Math.cos(a) * r; gy[i] = .5 + Math.sin(a) * r; tone[i] = .7 + rnd() * .3;
}
// every speck gets a seat in one pixel of the shades
const cells = [], cols = SHADES[0].length, cell = .84 / cols;
SHADES.forEach((row, r) => [...row].forEach((ch, c) => { if (ch !== '.') cells.push([(c + .5 - cols / 2) * cell, (r + .5 - SHADES.length / 2) * cell, ch === 'o']); }));
for (let i = 0; i < GRAINS; i++) {
const [cx, cy, bright] = cells[i % cells.length];
tx[i] = cx + (rnd() - .5) * cell * .96; ty[i] = cy + (rnd() - .5) * cell * .96; hot[i] = bright ? 1 : 0;
}
let mode = -1, rays = 0, rings = 0, twist = 0, shake = 0, pulse = 0, shades = false, st = 0, gy0 = TOP, gv = 0, nod = 0, nv = 0;
let S = 0, DPR = 1, img = null, buf = null, played = false, lastChord = -1;
// the disc stands still along these lines, and the dust settles there
function wave(x, y) {
const dx = x - .5, dy = y - .5;
const r = Math.hypot(dx, dy) / R, th = Math.atan2(dy, dx);
const a = cos(rays * (th - twist * r));
const b = cos(rings * PI * r);
return a * b;
}
function paintFloor() {
const c = floor.getContext('2d'), w = floor.width, m = w / 2, r = R * w;
c.clearRect(0, 0, w, w);
const g = c.createRadialGradient(m, m * .9, r * .1, m, m, r);
g.addColorStop(0, '#0B1610'); g.addColorStop(.75, '#070D0A'); g.addColorStop(1, '#040705');
c.fillStyle = g; c.beginPath(); c.arc(m, m, r, 0, 7); c.fill();
c.lineWidth = 1.5 * DPR; c.strokeStyle = 'rgba(52,232,154,.13)'; c.stroke();
c.lineWidth = 6 * DPR; c.strokeStyle = 'rgba(0,0,0,.5)'; c.beginPath(); c.arc(m, m, r + 4 * DPR, 0, 7); c.stroke();
}
function layout() {
const w = stage.clientWidth;
if (!w || w === S) return;
S = w; DPR = Math.min(2, window.devicePixelRatio || 1);
const px = Math.round(S * DPR);
floor.width = floor.height = px; dust.width = dust.height = px; page.width = page.height = px;
halo.width = halo.height = Math.ceil(px / 4);
img = pctx.createImageData(px, px); buf = img.data;
paintFloor();
grain.width = Math.round(root.clientWidth / 2); grain.height = Math.round(root.clientHeight / 2);
const gc = grain.getContext('2d'), gi = gc.createImageData(grain.width, grain.height);
for (let i = 0; i < gi.data.length; i += 4) { const v = rnd() * 255; gi.data[i] = gi.data[i + 1] = gi.data[i + 2] = v; gi.data[i + 3] = 12; }
gc.putImageData(gi, 0, 0);
}
// the sound: a piano made of three layers of overtones and a hammer, a round bass, a small drum machine
function Sound(ac, dest, rnd, tune) {
const comp = ac.createDynamicsCompressor(), master = ac.createGain(), room = ac.createConvolver(), wet = ac.createGain(), bus = ac.createGain(), wall = ac.createDynamicsCompressor();
comp.threshold.value = -18; comp.ratio.value = 4; master.gain.value = .5; wet.gain.value = .16;
wall.threshold.value = -3; wall.knee.value = 0; wall.ratio.value = 20; wall.attack.value = .002; wall.release.value = .12;
const sr = ac.sampleRate, len = Math.round(sr * 1.6), ir = ac.createBuffer(2, len, sr);
for (let c = 0; c < 2; c++) { const d = ir.getChannelData(c); for (let i = 0; i < len; i++) d[i] = (rnd() * 2 - 1) * Math.pow(1 - i / len, 3.5); }
room.buffer = ir;
bus.connect(comp); bus.connect(room); room.connect(wet); wet.connect(comp); comp.connect(master); master.connect(wall); wall.connect(dest);
const noise = ac.createBuffer(1, sr * 2, sr), nd = noise.getChannelData(0);
for (let i = 0; i < nd.length; i++) nd[i] = rnd() * 2 - 1;
const layer = (from, to, tilt) => {
const re = new Float32Array(to + 1), im = new Float32Array(to + 1);
for (let h = from; h <= to; h++) im[h] = 1 / Math.pow(h, tilt);
return ac.createPeriodicWave(re, im, { disableNormalization: true });
};
const LAYERS = [[layer(1, 3, 1), .9, .55], [layer(4, 8, 1.1), .45, .2], [layer(9, 18, 1.2), .25, .07]];
const hz = n => 440 * 2 ** ((n - 69 + tune / 100) / 12);
const burst = (t, type, freq, q, level, fall) => {
const s = ac.createBufferSource(), f = ac.createBiquadFilter(), g = ac.createGain();
s.buffer = noise; f.type = type; f.frequency.value = freq; f.Q.value = q;
g.gain.setValueAtTime(level, t); g.gain.setTargetAtTime(0, t + .002, fall);
s.connect(f).connect(g).connect(bus); s.start(t); s.stop(t + Math.min(2, fall * 8));
};
return {
key(n, t, level, hold) {
const f = hz(n), life = Math.min(1.2, .8 * Math.sqrt(262 / f));
for (const [shape, share, fall] of LAYERS) {
const o = ac.createOscillator(), g = ac.createGain();
o.setPeriodicWave(shape); o.frequency.value = f; o.detune.value = (rnd() - .5) * 5;
g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(level * share, t + .004);
g.gain.setTargetAtTime(level * share * .3, t + .004, life * fall); g.gain.setTargetAtTime(0, t + hold, .06);
o.connect(g).connect(bus); o.start(t); o.stop(t + hold + .5);
}
burst(t, 'bandpass', Math.min(5000, f * 7), 1.4, level * .35, .008);
},
bass(n, t) {
const o = ac.createOscillator(), g = ac.createGain();
o.setPeriodicWave(LAYERS[0][0]); o.frequency.value = hz(n);
g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(.42, t + .012); g.gain.setTargetAtTime(0, t + .03, 1.1);
o.connect(g).connect(comp); o.start(t); o.stop(t + 3);
},
kick(t, level = .95) {
const o = ac.createOscillator(), g = ac.createGain();
o.frequency.setValueAtTime(140, t); o.frequency.exponentialRampToValueAtTime(46, t + .11);
g.gain.setValueAtTime(level, t); g.gain.setTargetAtTime(0, t + .02, .13);
o.connect(g).connect(comp); o.start(t); o.stop(t + .9);
burst(t, 'lowpass', 900, .7, level * .3, .01);
},
snare(t) {
burst(t, 'bandpass', 1900, .7, .55, .06);
const o = ac.createOscillator(), g = ac.createGain();
o.type = 'triangle'; o.frequency.setValueAtTime(190, t); o.frequency.exponentialRampToValueAtTime(150, t + .06);
g.gain.setValueAtTime(.3, t); g.gain.setTargetAtTime(0, t + .005, .045);
o.connect(g).connect(bus); o.start(t); o.stop(t + .4);
},
hat(t, level) { burst(t, 'highpass', 7500, .7, level, .018); },
crash(t) { burst(t, 'highpass', 4500, .5, .22, .45); }
};
}
let audio = null, sound = null, soundOn = true;
function ear() {
if (audio) return audio;
const AC = window.AudioContext || window.webkitAudioContext;
if (!AC) return null;
audio = new AC(); sound = Sound(audio, audio.destination, rnd, TUNE);
return audio;
}
// a chord: three piano notes, and the bass whenever the chord moves to a new root
function chord(k, t) {
const [low, ...notes] = CHORDS[k];
notes.forEach(n => sound.key(n, t, .2, E * .92));
if (lastChord < 0 || CHORDS[lastChord][0] !== low) sound.bass(low, t);
}
// the drums run on the tempo of the riff from the moment the fourth switch was hit
let beatOn = false, beatAt = 0, heard = -1, audioAt = 0, fed = 0, timer = 0;
function drum(s, t) {
const i = s % 8;
if (KICK.includes(i)) sound.kick(t);
if (SNARE.includes(i)) sound.snare(t);
sound.hat(t, i % 2 ? .06 : .1);
}
function feed() {
if (!beatOn || !audio || !soundOn) return;
if (audioAt + fed * E < audio.currentTime - .05) fed = Math.ceil((audio.currentTime - audioAt) / E);
while (audioAt + fed * E < audio.currentTime + .15) { drum(fed, audioAt + fed * E); fed++; }
}
// a hit: the dust jumps, harder where the disc shakes most and harder still on a new chord
function jump(power) {
if (calm.matches) return;
for (let i = 0; i < GRAINS; i++) {
const f = mode < 0 ? 1 : Math.abs(wave(gx[i], gy[i]));
rise[i] += HOP * power * (.3 + .7 * f) * (.6 + .4 * rnd());
}
}
function sparkle(share) {
if (calm.matches) return;
for (let i = 0; i < GRAINS; i++) if (rnd() < share) rise[i] += HOP * .3 * rnd();
}
function build() {
shades = true; st = 0; gy0 = TOP; gv = 0; nod = 0; nv = 0;
for (let i = 0; i < GRAINS; i++) { vx[i] = (rnd() - .5) * .5; vy[i] = -(.25 + rnd() * .5); wait[i] = .12 + rnd() * .25; up[i] = 0; rise[i] = 0; }
}
function hit(k) {
const on = soundOn && ear(), t = on ? audio.currentTime + .01 : 0;
if (on && audio.state !== 'running') audio.resume();
if (k === 3) {
if (shades) {
shades = false; beatOn = false; clearInterval(timer); mode = -1; shake = 2.6; jump(1.3);
if (on) sound.kick(t, .5);
} else {
build();
beatOn = true; beatAt = performance.now() / 1000; heard = -1; fed = 0;
if (audio) audioAt = audio.currentTime + .01;
if (on) { chord(0, t); sound.crash(t); feed(); }
clearInterval(timer); timer = setInterval(feed, 25);
lastChord = 0;
}
} else {
if (shades) sparkle(.6);
else { shake = 1; const fresh = mode !== k; mode = k; [rays, rings, twist] = SHAPES[k]; jump(fresh ? 1.35 : 1); }
if (on) chord(k, t);
lastChord = k;
}
pulse = 1; played = true;
sw[3].classList.toggle('is-on', shades);
led[k].animate([{ opacity: 1 }, { opacity: shades && k === 3 ? .85 : 0 }], { duration: 380, easing: 'cubic-bezier(.23, 1, .32, 1)' });
}
// the switches flip down while held and spring back; a quick tap still shows the flip
const flip = [1, 1, 1, 1], fv = [0, 0, 0, 0], goal = [1, 1, 1, 1], upAt = [0, 0, 0, 0], wantUp = [false, false, false, false];
function press(k) { hit(k); goal[k] = -1; wantUp[k] = false; upAt[k] = performance.now() + 90; }
function release(k) { wantUp[k] = true; if (audio && audio.state !== 'running' && soundOn) audio.resume(); }
sw.forEach((b, k) => {
b.addEventListener('pointerdown', e => { e.preventDefault(); press(k); });
for (const type of ['pointerup', 'pointercancel', 'pointerleave']) b.addEventListener(type, () => release(k));
b.addEventListener('click', e => { if (e.detail === 0) { press(k); release(k); } });
});
let seen = true;
new IntersectionObserver(list => { seen = list[0].isIntersecting; }).observe(root);
const CODES = ['KeyA', 'KeyS', 'KeyD', 'KeyF'];
addEventListener('keydown', e => {
const k = CODES.indexOf(e.code), t = e.target;
if (k < 0 || e.repeat || e.metaKey || e.ctrlKey || e.altKey || !seen) return;
if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
e.preventDefault(); press(k);
});
addEventListener('keyup', e => { const k = CODES.indexOf(e.code); if (k >= 0) release(k); });
soundBtn.addEventListener('click', () => {
soundOn = !soundOn;
soundBtn.setAttribute('aria-pressed', String(soundOn));
if (soundOn && ear()) { audio.resume(); audioAt = audio.currentTime - ((performance.now() / 1000 - beatAt) % E) + E; fed = 0; }
});
function levers(dt, now, still) {
for (let k = 0; k < 4; k++) {
if (wantUp[k] && now >= upAt[k]) { goal[k] = 1; wantUp[k] = false; }
if (still) flip[k] = goal[k];
else for (let s = Math.ceil(dt / .008), h = dt / s; s > 0; s--) {
fv[k] += ((goal[k] - flip[k]) * 900 - fv[k] * 40) * h;
flip[k] += fv[k] * h;
}
lever[k].style.transform = `scaleY(${flip[k].toFixed(3)})`;
tip[k].style.opacity = Math.max(0, 1 - Math.abs(flip[k]) * 2.5).toFixed(2);
}
}
// the dust wanders less where the disc is still, so it piles up on the quiet lines
function wander(dt) {
if (shake < .002) { shake = 0; return; }
const hops = Math.max(1, Math.round(dt * 210));
for (let k = 0; k < hops; k++) for (let i = 0; i < GRAINS; i++) {
const f = mode < 0 ? 1 : Math.abs(wave(gx[i], gy[i]));
const step = JUMP * shake * f;
gx[i] += (rnd() - .5) * step;
gy[i] += (rnd() - .5) * step;
const dx = gx[i] - .5, dy = gy[i] - .5, d = Math.hypot(dx, dy);
if (d > R) { gx[i] = .5 + dx * R / d; gy[i] = .5 + dy * R / d; }
}
shake *= Math.exp(-dt / SETTLE);
}
// a speck in the air falls back by gravity and lands before the next eighth note
function fall(dt) {
for (let i = 0; i < GRAINS; i++) {
if (up[i] <= 0 && rise[i] <= 0) continue;
rise[i] -= 2600 * dt; up[i] += rise[i] * dt;
if (up[i] <= 0) { up[i] = 0; rise[i] = 0; }
}
}
// the shades: the dust flies up, takes its seats at the top, the pair slides down on a spring and nods to the kick
function gather(dt, still) {
st += dt;
if (still) gy0 = MID;
else {
const want = st < .7 ? TOP : MID;
for (let s = Math.ceil(dt / .008), h = dt / s; s > 0; s--) {
gv += ((want - gy0) * 160 - gv * 17) * h; gy0 += gv * h;
nv += (-nod * 420 - nv * 16) * h; nod += nv * h;
}
}
const lock = 1 - Math.exp(-dt * (st < .7 ? 7 : 24));
for (let i = 0; i < GRAINS; i++) {
if (!still && st < wait[i]) { gx[i] += vx[i] * dt; gy[i] += vy[i] * dt; vy[i] += 1.4 * dt; continue; }
gx[i] += (.5 + tx[i] - gx[i]) * lock;
gy[i] += (gy0 + nod + ty[i] - gy[i]) * lock;
}
}
// the beat seen: each kick nods the shades, each snare flashes them
function listen(now) {
if (!beatOn) return;
const s = Math.floor((now / 1000 - beatAt) / E + 1e-6);
while (heard < s) {
heard++;
const i = heard % 8;
if (KICK.includes(i)) { nv += .24; pulse = Math.max(pulse, .7); }
if (SNARE.includes(i)) { pulse = 1; sparkle(.35); }
}
}
function frame(now) {
const dt = Math.min(.05, frame.t ? (now - frame.t) / 1000 : .016);
frame.t = now;
requestAnimationFrame(frame);
if (!S) return;
const still = calm.matches;
levers(dt, now, still);
listen(now);
if (shades) gather(dt, still); else wander(dt);
fall(dt);
pulse *= Math.exp(-dt / .16);
stage.style.transform = pulse > .01 && !still ? `scale(${(1 + pulse * .014).toFixed(4)})` : '';
draw(now, still);
hint.style.opacity = played ? '0' : '1';
}
// every speck is a point of green light; where they crowd the light turns to mint, a speck in the air shines brighter
function draw(now, still) {
const w = dust.width, size = (DPR > 1.4 ? 2 : 1) + (shades ? 1 : 0), tw = now / 1000, boost = 1 + pulse * .45;
buf.fill(0);
for (let i = 0; i < GRAINS; i++) {
const sx = (gx[i] * w) | 0, sy = (gy[i] * w - up[i] * DPR) | 0;
if (sx < 0 || sy < 0 || sx >= w - 3 || sy >= w - 3) continue;
const b = tone[i] * (still ? 1 : .82 + .18 * Math.sin(tw * 2.2 + i)) * (150 + up[i] * 3) * boost;
const bright = shades && hot[i], r = bright ? b * 1.3 : b * .22, g = bright ? b * 1.6 : b, bl = bright ? b * 1.45 : b * .66;
for (let oy = 0; oy < size; oy++) for (let ox = 0; ox < size; ox++) {
const o = ((sy + oy) * w + sx + ox) * 4;
buf[o] += r; buf[o + 1] += g; buf[o + 2] += bl; buf[o + 3] = 255;
}
}
pctx.putImageData(img, 0, 0);
ctx.clearRect(0, 0, w, w);
hctx.clearRect(0, 0, halo.width, halo.height); hctx.imageSmoothingQuality = 'high';
hctx.drawImage(page, 0, 0, halo.width, halo.height);
ctx.globalCompositeOperation = 'lighter'; ctx.imageSmoothingQuality = 'high';
ctx.globalAlpha = Math.min(1, .5 + pulse * .6); ctx.drawImage(halo, 0, 0, w, w); ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(page, 0, 0);
}
new ResizeObserver(layout).observe(stage);
layout();
requestAnimationFrame(frame);
})();
</script>
Tap the first three switches in rhythm, then the fourth. The keys A S D F play too. Sound is on, the Sound button turns it off.
What you can change
Change a number, save, and reload the page to see the difference.
GRAINS9000How many specks of dust, fewer is lighter for slow phones.
JUMP0.06How far a speck wanders on a hit, as a share of the disc.
SETTLE0.35How long the disc keeps shaking after a hit, in seconds.
HOP320How high the dust jumps on a hit, in pixels per second.
TEMPO94The tempo of the drums, in beats per minute.
TUNE50The tuning in cents. 50 sits a quarter tone sharp like a sped-up record, 0 is standard pitch.
Add it to your site
A music page, an artist or a studio site, a hero section people come back to just to play.
CSS
Paste into your stylesheet, or inside a <style> tag in <head>.
/* Riff Shades by @codinvisual · t.me/CodinVisual · page shell, only needed while this file is the whole page */HTML
Put it where the effect should appear on your page.
<!-- riff start --> <div class="rs"> <canvas class="rs-grain" aria-hidden="true"></canvas> <div class="rs-stage" aria-hidden="true"><canvas class="rs-floor"></canvas><canvas class="rs-dust"></canvas></div> <div class="rs-box"> <button class="rs-sw" type="button" aria-label="First chord"><span class="rs-led"><i></i></span><span class="rs-nut"></span><span class="rs-lever"></span><span class="rs-tip"></span><span class="rs-key">A</span></button> <button class="rs-sw" type="button" aria-label="Second chord"><span class="rs-led"><i></i></span><span class="rs-nut"></span><span class="rs-lever"></span><span class="rs-tip"></span><span class="rs-key">S</span></button> <button class="rs-sw" type="button" aria-label="Third chord"><span class="rs-led"><i></i></span><span class="rs-nut"></span><span class="rs-lever"></span><span class="rs-tip"></span><span class="rs-key">D</span></button> <button class="rs-sw" type="button" aria-label="Drop the shades"><span class="rs-led"><i></i></span><span class="rs-nut"></span><span class="rs-lever"></span><span class="rs-tip"></span><span class="rs-key"><svg viewBox="0 0 12 5" width="17" height="7" aria-hidden="true" fill="currentColor"><path d="M0 0h12v1H11v2h-1v1H8V3H7V1H5v2H4v1H2V3H1V1H0z"/></svg>F</span></button> </div> <button class="rs-sound" type="button" aria-pressed="true"><svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M4 9.5h3.5L12 5.5v13L7.5 14.5H4z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/><path d="M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg><span>Sound</span></button> <p class="rs-hint" aria-hidden="true">Play the switches<span class="rs-keys"> · keys A S D F</span></p> </div> <!-- riff end -->JavaScript
Paste right before the closing </body> tag, inside <script></script>.
/* Riff Shades by @codinvisual · t.me/CodinVisual · free for your own site, don't resell this file */ (() => { const GRAINS = 9000; const JUMP = 0.06; const SETTLE = 0.35; const HOP = 320; const TEMPO = 94; const TUNE = 50; const CHORDS = [ [45, 72, 76, 81], [40, 71, 76, 81], [40, 71, 76, 79] ]; const KICK = [0, 4, 5], SNARE = [2, 6]; const SHAPES = [[4, 1.5, 0], [0, 3.5, 0], [5, .5, 2.6]]; const SHADES = [ '########################', '..##########..##########', '..##oo######..##oo######', '..####oo####..####oo####', '....######......######..' ]; const root = document.querySelector('.rs'); if (!root) return; const stage = root.querySelector('.rs-stage'), floor = root.querySelector('.rs-floor'), dust = root.querySelector('.rs-dust'); const sw = [...root.querySelectorAll('.rs-sw')], soundBtn = root.querySelector('.rs-sound'), hint = root.querySelector('.rs-hint'), grain = root.querySelector('.rs-grain'); const lever = sw.map(b => b.querySelector('.rs-lever')), tip = sw.map(b => b.querySelector('.rs-tip')), led = sw.map(b => b.querySelector('.rs-led i')); const calm = matchMedia('(prefers-reduced-motion: reduce)'); const ctx = dust.getContext('2d'), page = document.createElement('canvas'), pctx = page.getContext('2d'); const halo = document.createElement('canvas'), hctx = halo.getContext('2d'); const { cos, PI } = Math; const R = .44, TOP = .2, MID = .5, E = 30 / TEMPO; let seed = 1017; const rnd = () => { seed = seed + 0x6D2B79F5 | 0; let t = Math.imul(seed ^ seed >>> 15, 1 | seed); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; // dust lives in stage units, 0 to 1 across; at first it is simply spread over the disc const gx = new Float32Array(GRAINS), gy = new Float32Array(GRAINS), up = new Float32Array(GRAINS), rise = new Float32Array(GRAINS), tone = new Float32Array(GRAINS); const tx = new Float32Array(GRAINS), ty = new Float32Array(GRAINS), vx = new Float32Array(GRAINS), vy = new Float32Array(GRAINS), wait = new Float32Array(GRAINS), hot = new Uint8Array(GRAINS); for (let i = 0; i < GRAINS; i++) { const r = R * Math.sqrt(rnd()) * .98, a = rnd() * PI * 2; gx[i] = .5 + Math.cos(a) * r; gy[i] = .5 + Math.sin(a) * r; tone[i] = .7 + rnd() * .3; } // every speck gets a seat in one pixel of the shades const cells = [], cols = SHADES[0].length, cell = .84 / cols; SHADES.forEach((row, r) => [...row].forEach((ch, c) => { if (ch !== '.') cells.push([(c + .5 - cols / 2) * cell, (r + .5 - SHADES.length / 2) * cell, ch === 'o']); })); for (let i = 0; i < GRAINS; i++) { const [cx, cy, bright] = cells[i % cells.length]; tx[i] = cx + (rnd() - .5) * cell * .96; ty[i] = cy + (rnd() - .5) * cell * .96; hot[i] = bright ? 1 : 0; } let mode = -1, rays = 0, rings = 0, twist = 0, shake = 0, pulse = 0, shades = false, st = 0, gy0 = TOP, gv = 0, nod = 0, nv = 0; let S = 0, DPR = 1, img = null, buf = null, played = false, lastChord = -1; // the disc stands still along these lines, and the dust settles there function wave(x, y) { const dx = x - .5, dy = y - .5; const r = Math.hypot(dx, dy) / R, th = Math.atan2(dy, dx); const a = cos(rays * (th - twist * r)); const b = cos(rings * PI * r); return a * b; } function paintFloor() { const c = floor.getContext('2d'), w = floor.width, m = w / 2, r = R * w; c.clearRect(0, 0, w, w); const g = c.createRadialGradient(m, m * .9, r * .1, m, m, r); g.addColorStop(0, '#0B1610'); g.addColorStop(.75, '#070D0A'); g.addColorStop(1, '#040705'); c.fillStyle = g; c.beginPath(); c.arc(m, m, r, 0, 7); c.fill(); c.lineWidth = 1.5 * DPR; c.strokeStyle = 'rgba(52,232,154,.13)'; c.stroke(); c.lineWidth = 6 * DPR; c.strokeStyle = 'rgba(0,0,0,.5)'; c.beginPath(); c.arc(m, m, r + 4 * DPR, 0, 7); c.stroke(); } function layout() { const w = stage.clientWidth; if (!w || w === S) return; S = w; DPR = Math.min(2, window.devicePixelRatio || 1); const px = Math.round(S * DPR); floor.width = floor.height = px; dust.width = dust.height = px; page.width = page.height = px; halo.width = halo.height = Math.ceil(px / 4); img = pctx.createImageData(px, px); buf = img.data; paintFloor(); grain.width = Math.round(root.clientWidth / 2); grain.height = Math.round(root.clientHeight / 2); const gc = grain.getContext('2d'), gi = gc.createImageData(grain.width, grain.height); for (let i = 0; i < gi.data.length; i += 4) { const v = rnd() * 255; gi.data[i] = gi.data[i + 1] = gi.data[i + 2] = v; gi.data[i + 3] = 12; } gc.putImageData(gi, 0, 0); } // the sound: a piano made of three layers of overtones and a hammer, a round bass, a small drum machine function Sound(ac, dest, rnd, tune) { const comp = ac.createDynamicsCompressor(), master = ac.createGain(), room = ac.createConvolver(), wet = ac.createGain(), bus = ac.createGain(), wall = ac.createDynamicsCompressor(); comp.threshold.value = -18; comp.ratio.value = 4; master.gain.value = .5; wet.gain.value = .16; wall.threshold.value = -3; wall.knee.value = 0; wall.ratio.value = 20; wall.attack.value = .002; wall.release.value = .12; const sr = ac.sampleRate, len = Math.round(sr * 1.6), ir = ac.createBuffer(2, len, sr); for (let c = 0; c < 2; c++) { const d = ir.getChannelData(c); for (let i = 0; i < len; i++) d[i] = (rnd() * 2 - 1) * Math.pow(1 - i / len, 3.5); } room.buffer = ir; bus.connect(comp); bus.connect(room); room.connect(wet); wet.connect(comp); comp.connect(master); master.connect(wall); wall.connect(dest); const noise = ac.createBuffer(1, sr * 2, sr), nd = noise.getChannelData(0); for (let i = 0; i < nd.length; i++) nd[i] = rnd() * 2 - 1; const layer = (from, to, tilt) => { const re = new Float32Array(to + 1), im = new Float32Array(to + 1); for (let h = from; h <= to; h++) im[h] = 1 / Math.pow(h, tilt); return ac.createPeriodicWave(re, im, { disableNormalization: true }); }; const LAYERS = [[layer(1, 3, 1), .9, .55], [layer(4, 8, 1.1), .45, .2], [layer(9, 18, 1.2), .25, .07]]; const hz = n => 440 * 2 ** ((n - 69 + tune / 100) / 12); const burst = (t, type, freq, q, level, fall) => { const s = ac.createBufferSource(), f = ac.createBiquadFilter(), g = ac.createGain(); s.buffer = noise; f.type = type; f.frequency.value = freq; f.Q.value = q; g.gain.setValueAtTime(level, t); g.gain.setTargetAtTime(0, t + .002, fall); s.connect(f).connect(g).connect(bus); s.start(t); s.stop(t + Math.min(2, fall * 8)); }; return { key(n, t, level, hold) { const f = hz(n), life = Math.min(1.2, .8 * Math.sqrt(262 / f)); for (const [shape, share, fall] of LAYERS) { const o = ac.createOscillator(), g = ac.createGain(); o.setPeriodicWave(shape); o.frequency.value = f; o.detune.value = (rnd() - .5) * 5; g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(level * share, t + .004); g.gain.setTargetAtTime(level * share * .3, t + .004, life * fall); g.gain.setTargetAtTime(0, t + hold, .06); o.connect(g).connect(bus); o.start(t); o.stop(t + hold + .5); } burst(t, 'bandpass', Math.min(5000, f * 7), 1.4, level * .35, .008); }, bass(n, t) { const o = ac.createOscillator(), g = ac.createGain(); o.setPeriodicWave(LAYERS[0][0]); o.frequency.value = hz(n); g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(.42, t + .012); g.gain.setTargetAtTime(0, t + .03, 1.1); o.connect(g).connect(comp); o.start(t); o.stop(t + 3); }, kick(t, level = .95) { const o = ac.createOscillator(), g = ac.createGain(); o.frequency.setValueAtTime(140, t); o.frequency.exponentialRampToValueAtTime(46, t + .11); g.gain.setValueAtTime(level, t); g.gain.setTargetAtTime(0, t + .02, .13); o.connect(g).connect(comp); o.start(t); o.stop(t + .9); burst(t, 'lowpass', 900, .7, level * .3, .01); }, snare(t) { burst(t, 'bandpass', 1900, .7, .55, .06); const o = ac.createOscillator(), g = ac.createGain(); o.type = 'triangle'; o.frequency.setValueAtTime(190, t); o.frequency.exponentialRampToValueAtTime(150, t + .06); g.gain.setValueAtTime(.3, t); g.gain.setTargetAtTime(0, t + .005, .045); o.connect(g).connect(bus); o.start(t); o.stop(t + .4); }, hat(t, level) { burst(t, 'highpass', 7500, .7, level, .018); }, crash(t) { burst(t, 'highpass', 4500, .5, .22, .45); } }; } let audio = null, sound = null, soundOn = true; function ear() { if (audio) return audio; const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return null; audio = new AC(); sound = Sound(audio, audio.destination, rnd, TUNE); return audio; } // a chord: three piano notes, and the bass whenever the chord moves to a new root function chord(k, t) { const [low, ...notes] = CHORDS[k]; notes.forEach(n => sound.key(n, t, .2, E * .92)); if (lastChord < 0 || CHORDS[lastChord][0] !== low) sound.bass(low, t); } // the drums run on the tempo of the riff from the moment the fourth switch was hit let beatOn = false, beatAt = 0, heard = -1, audioAt = 0, fed = 0, timer = 0; function drum(s, t) { const i = s % 8; if (KICK.includes(i)) sound.kick(t); if (SNARE.includes(i)) sound.snare(t); sound.hat(t, i % 2 ? .06 : .1); } function feed() { if (!beatOn || !audio || !soundOn) return; if (audioAt + fed * E < audio.currentTime - .05) fed = Math.ceil((audio.currentTime - audioAt) / E); while (audioAt + fed * E < audio.currentTime + .15) { drum(fed, audioAt + fed * E); fed++; } } // a hit: the dust jumps, harder where the disc shakes most and harder still on a new chord function jump(power) { if (calm.matches) return; for (let i = 0; i < GRAINS; i++) { const f = mode < 0 ? 1 : Math.abs(wave(gx[i], gy[i])); rise[i] += HOP * power * (.3 + .7 * f) * (.6 + .4 * rnd()); } } function sparkle(share) { if (calm.matches) return; for (let i = 0; i < GRAINS; i++) if (rnd() < share) rise[i] += HOP * .3 * rnd(); } function build() { shades = true; st = 0; gy0 = TOP; gv = 0; nod = 0; nv = 0; for (let i = 0; i < GRAINS; i++) { vx[i] = (rnd() - .5) * .5; vy[i] = -(.25 + rnd() * .5); wait[i] = .12 + rnd() * .25; up[i] = 0; rise[i] = 0; } } function hit(k) { const on = soundOn && ear(), t = on ? audio.currentTime + .01 : 0; if (on && audio.state !== 'running') audio.resume(); if (k === 3) { if (shades) { shades = false; beatOn = false; clearInterval(timer); mode = -1; shake = 2.6; jump(1.3); if (on) sound.kick(t, .5); } else { build(); beatOn = true; beatAt = performance.now() / 1000; heard = -1; fed = 0; if (audio) audioAt = audio.currentTime + .01; if (on) { chord(0, t); sound.crash(t); feed(); } clearInterval(timer); timer = setInterval(feed, 25); lastChord = 0; } } else { if (shades) sparkle(.6); else { shake = 1; const fresh = mode !== k; mode = k; [rays, rings, twist] = SHAPES[k]; jump(fresh ? 1.35 : 1); } if (on) chord(k, t); lastChord = k; } pulse = 1; played = true; sw[3].classList.toggle('is-on', shades); led[k].animate([{ opacity: 1 }, { opacity: shades && k === 3 ? .85 : 0 }], { duration: 380, easing: 'cubic-bezier(.23, 1, .32, 1)' }); } // the switches flip down while held and spring back; a quick tap still shows the flip const flip = [1, 1, 1, 1], fv = [0, 0, 0, 0], goal = [1, 1, 1, 1], upAt = [0, 0, 0, 0], wantUp = [false, false, false, false]; function press(k) { hit(k); goal[k] = -1; wantUp[k] = false; upAt[k] = performance.now() + 90; } function release(k) { wantUp[k] = true; if (audio && audio.state !== 'running' && soundOn) audio.resume(); } sw.forEach((b, k) => { b.addEventListener('pointerdown', e => { e.preventDefault(); press(k); }); for (const type of ['pointerup', 'pointercancel', 'pointerleave']) b.addEventListener(type, () => release(k)); b.addEventListener('click', e => { if (e.detail === 0) { press(k); release(k); } }); }); let seen = true; new IntersectionObserver(list => { seen = list[0].isIntersecting; }).observe(root); const CODES = ['KeyA', 'KeyS', 'KeyD', 'KeyF']; addEventListener('keydown', e => { const k = CODES.indexOf(e.code), t = e.target; if (k < 0 || e.repeat || e.metaKey || e.ctrlKey || e.altKey || !seen) return; if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return; e.preventDefault(); press(k); }); addEventListener('keyup', e => { const k = CODES.indexOf(e.code); if (k >= 0) release(k); }); soundBtn.addEventListener('click', () => { soundOn = !soundOn; soundBtn.setAttribute('aria-pressed', String(soundOn)); if (soundOn && ear()) { audio.resume(); audioAt = audio.currentTime - ((performance.now() / 1000 - beatAt) % E) + E; fed = 0; } }); function levers(dt, now, still) { for (let k = 0; k < 4; k++) { if (wantUp[k] && now >= upAt[k]) { goal[k] = 1; wantUp[k] = false; } if (still) flip[k] = goal[k]; else for (let s = Math.ceil(dt / .008), h = dt / s; s > 0; s--) { fv[k] += ((goal[k] - flip[k]) * 900 - fv[k] * 40) * h; flip[k] += fv[k] * h; } lever[k].style.transform = `scaleY(${flip[k].toFixed(3)})`; tip[k].style.opacity = Math.max(0, 1 - Math.abs(flip[k]) * 2.5).toFixed(2); } } // the dust wanders less where the disc is still, so it piles up on the quiet lines function wander(dt) { if (shake < .002) { shake = 0; return; } const hops = Math.max(1, Math.round(dt * 210)); for (let k = 0; k < hops; k++) for (let i = 0; i < GRAINS; i++) { const f = mode < 0 ? 1 : Math.abs(wave(gx[i], gy[i])); const step = JUMP * shake * f; gx[i] += (rnd() - .5) * step; gy[i] += (rnd() - .5) * step; const dx = gx[i] - .5, dy = gy[i] - .5, d = Math.hypot(dx, dy); if (d > R) { gx[i] = .5 + dx * R / d; gy[i] = .5 + dy * R / d; } } shake *= Math.exp(-dt / SETTLE); } // a speck in the air falls back by gravity and lands before the next eighth note function fall(dt) { for (let i = 0; i < GRAINS; i++) { if (up[i] <= 0 && rise[i] <= 0) continue; rise[i] -= 2600 * dt; up[i] += rise[i] * dt; if (up[i] <= 0) { up[i] = 0; rise[i] = 0; } } } // the shades: the dust flies up, takes its seats at the top, the pair slides down on a spring and nods to the kick function gather(dt, still) { st += dt; if (still) gy0 = MID; else { const want = st < .7 ? TOP : MID; for (let s = Math.ceil(dt / .008), h = dt / s; s > 0; s--) { gv += ((want - gy0) * 160 - gv * 17) * h; gy0 += gv * h; nv += (-nod * 420 - nv * 16) * h; nod += nv * h; } } const lock = 1 - Math.exp(-dt * (st < .7 ? 7 : 24)); for (let i = 0; i < GRAINS; i++) { if (!still && st < wait[i]) { gx[i] += vx[i] * dt; gy[i] += vy[i] * dt; vy[i] += 1.4 * dt; continue; } gx[i] += (.5 + tx[i] - gx[i]) * lock; gy[i] += (gy0 + nod + ty[i] - gy[i]) * lock; } } // the beat seen: each kick nods the shades, each snare flashes them function listen(now) { if (!beatOn) return; const s = Math.floor((now / 1000 - beatAt) / E + 1e-6); while (heard < s) { heard++; const i = heard % 8; if (KICK.includes(i)) { nv += .24; pulse = Math.max(pulse, .7); } if (SNARE.includes(i)) { pulse = 1; sparkle(.35); } } } function frame(now) { const dt = Math.min(.05, frame.t ? (now - frame.t) / 1000 : .016); frame.t = now; requestAnimationFrame(frame); if (!S) return; const still = calm.matches; levers(dt, now, still); listen(now); if (shades) gather(dt, still); else wander(dt); fall(dt); pulse *= Math.exp(-dt / .16); stage.style.transform = pulse > .01 && !still ? `scale(${(1 + pulse * .014).toFixed(4)})` : ''; draw(now, still); hint.style.opacity = played ? '0' : '1'; } // every speck is a point of green light; where they crowd the light turns to mint, a speck in the air shines brighter function draw(now, still) { const w = dust.width, size = (DPR > 1.4 ? 2 : 1) + (shades ? 1 : 0), tw = now / 1000, boost = 1 + pulse * .45; buf.fill(0); for (let i = 0; i < GRAINS; i++) { const sx = (gx[i] * w) | 0, sy = (gy[i] * w - up[i] * DPR) | 0; if (sx < 0 || sy < 0 || sx >= w - 3 || sy >= w - 3) continue; const b = tone[i] * (still ? 1 : .82 + .18 * Math.sin(tw * 2.2 + i)) * (150 + up[i] * 3) * boost; const bright = shades && hot[i], r = bright ? b * 1.3 : b * .22, g = bright ? b * 1.6 : b, bl = bright ? b * 1.45 : b * .66; for (let oy = 0; oy < size; oy++) for (let ox = 0; ox < size; ox++) { const o = ((sy + oy) * w + sx + ox) * 4; buf[o] += r; buf[o + 1] += g; buf[o + 2] += bl; buf[o + 3] = 255; } } pctx.putImageData(img, 0, 0); ctx.clearRect(0, 0, w, w); hctx.clearRect(0, 0, halo.width, halo.height); hctx.imageSmoothingQuality = 'high'; hctx.drawImage(page, 0, 0, halo.width, halo.height); ctx.globalCompositeOperation = 'lighter'; ctx.imageSmoothingQuality = 'high'; ctx.globalAlpha = Math.min(1, .5 + pulse * .6); ctx.drawImage(halo, 0, 0, w, w); ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'; ctx.drawImage(page, 0, 0); } new ResizeObserver(layout).observe(stage); layout(); requestAnimationFrame(frame); })();
Good to know
- The sound is made in the browser, there are no audio files.
- CHORDS, KICK, SNARE and SHAPES set the notes, the drum pattern and the figure of each chord. SHADES is the pixel picture of the fourth switch, draw your own.
- The keys only play while the block is on screen and never while someone types in a field.
- With reduced motion turned on the dust does not jump and the shades appear in place. The figures, the beat and the sound stay.
Tilda, Webflow, WordPress
Press Copy all code at the top and paste it into one HTML block.
Add block, Other, T123 HTML code. Paste and save. Check the published page, the editor preview does not run scripts.
Add panel, Embed. Paste, then Save & Close. Custom code runs on the published site.
Add block, Custom HTML. Paste and press Update.



