Brand
ASCII trail
A mouse leaves a short trail of ASCII characters that fades in 700ms, over one section or, fixed behind it, the whole page. Only for a fine pointer; off on touch and with reduced motion.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add ascii-trail<script type="module" src="/spyglass-ds/elements/ascii-trail.js"></script>Move the pointer here.
The trail fades in 700ms and stays off on touch and with reduced motion.
Usage
A quiet response to the pointer on a page head, a 404 or a coming-soon page, behind the content.
Never
- Over text people read: it sits behind the content
- On touch, or with reduced motion
- Two on one page (a page trail and a section trail)
Adds with it: light-image
Props
The web component takes the same as attributes or properties (<spyglass-ascii-trail>); title is heading there.
<AsciiTrail>
| Prop | Type | Default |
|---|---|---|
mode | 'section' | 'page' section (absolute in its section) or page (fixed behind the page). | 'section' |
className | string |
Examples
The same example in React and as web components; both render identically.
import { AsciiTrail } from '@/react/components/visuals/AsciiTrail'
// A section with the trail: move a mouse across it (768 wide and up) and characters follow the pointer, then fade.
export default function Section() {
return (
<section className="relative isolate flex h-96 flex-col items-center justify-center gap-4 overflow-clip rounded-container bg-surface px-6 text-center inset-ring inset-ring-edge">
<AsciiTrail className="inset-0 -z-1 size-full" />
<h2 className="type-heading-2 text-fg">Move the pointer here.</h2>
<p className="type-body text-fg-muted">The trail fades in 700ms and stays off on touch and with reduced motion.</p>
</section>
)
}<!-- A section with the trail: move a mouse across it (768 wide and up) and characters follow the pointer, then fade. -->
<section class="relative isolate flex h-96 flex-col items-center justify-center gap-4 overflow-clip rounded-container bg-surface px-6 text-center inset-ring inset-ring-edge">
<spyglass-ascii-trail class="inset-0 -z-1 size-full"></spyglass-ascii-trail>
<h2 class="type-heading-2 text-fg">Move the pointer here.</h2>
<p class="type-body text-fg-muted">The trail fades in 700ms and stays off on touch and with reduced motion.</p>
</section>Source
'use client'
import { useEffect, useRef } from 'react'
import { whilePointerEffects } from '@/lib/effects/pointer'
import { cn } from '@/react/lib/cn'
// The site's ASCII trail (effect/AsciiTrail): a mouse leaves a short trail of ASCII characters that fades in 700ms. In
// `section` mode the canvas is absolute in its section (the classes size it, `inset-0`) and follows the pointer over the
// section; in `page` mode it is fixed behind the whole page. Only for a fine pointer on a screen 768 wide or more, and
// off with reduced motion; on touch it draws nothing. Decoration: hidden from assistive tech.
export interface AsciiTrailProps {
/** section (absolute in its section) or page (fixed behind the page). */
mode?: 'section' | 'page'
className?: string
}
export function AsciiTrail({ mode = 'section', className }: AsciiTrailProps) {
const ref = useRef<HTMLCanvasElement>(null)
useEffect(() => {
const canvas = ref.current
if (!canvas) return
return whilePointerEffects(() => import('@/lib/effects/ascii-trail').then(({ startTrail }) => startTrail(canvas, mode)))
}, [mode])
return <canvas ref={ref} data-ds="ascii-trail" data-ascii-trail={mode} aria-hidden="true" className={cn('pointer-events-none block text-fg', mode === 'page' ? 'fixed inset-0 -z-1 size-full' : 'absolute', className)} />
}
export default AsciiTrail// The site's ASCII trail (effect/AsciiTrail/trail): a mouse leaves a short trail of ASCII characters (" .:-=+*#",
// 8 by 16 cells) within --ds-ascii-trail-radius (72px) of the pointer, fading over --ds-ascii-trail-fade (700ms), at
// the texture's 0.35 in the canvas's text colour. Section mode listens on the section; page mode on the window, drawn
// fixed behind the page. Started only for a fine pointer without reduced motion (the components check).
const CELL_W = 8;
const CELL_H = 16;
const RAMP = " .:-=+*#";
const token = (el: Element, name: string) => parseFloat(getComputedStyle(el).getPropertyValue(name)) || 0;
const ms = (el: Element, name: string) => {
const raw = getComputedStyle(el).getPropertyValue(name).trim();
const n = parseFloat(raw) || 0;
return raw.endsWith("ms") ? n : raw.endsWith("s") ? n * 1000 : n;
};
export function startTrail(canvas: HTMLCanvasElement, mode: "section" | "page", section?: HTMLElement | null): () => void {
const page = mode === "page";
const host = page ? document.documentElement : (section ?? canvas.parentElement);
const ctx = canvas.getContext("2d");
if (!host || !ctx) return () => {};
const radius = token(canvas, "--ds-ascii-trail-radius") || 72;
const fade = ms(canvas, "--ds-ascii-trail-fade") || 700;
const strength = token(canvas, "--ds-ascii-opacity") || 0.35;
const family = getComputedStyle(canvas).getPropertyValue("--ds-font-ascii").trim() || "monospace";
const ink = getComputedStyle(canvas).color;
let cols = 0;
let rows = 0;
let heat = new Float32Array(0);
let seed = new Float32Array(0);
let raf = 0;
let last = 0;
const size = () => {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const w = page ? window.innerWidth : host.clientWidth;
const h = page ? window.innerHeight : canvas.clientHeight;
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.font = `13.333px ${family}`;
ctx.textBaseline = "top";
cols = Math.ceil(w / CELL_W);
rows = Math.ceil(h / CELL_H);
heat = new Float32Array(cols * rows);
seed = new Float32Array(cols * rows).map((_, i) => (((Math.sin(i * 12.9898) * 43758.5453) % 1) + 1) % 1);
};
const frame = (now: number) => {
const dt = last ? now - last : 16;
last = now;
const keep = Math.exp(-dt / fade);
ctx.clearRect(0, 0, cols * CELL_W, rows * CELL_H);
let warm = false;
for (let i = 0; i < heat.length; i++) {
const v = heat[i] * keep;
heat[i] = v < 0.01 ? 0 : v;
if (!heat[i]) continue;
warm = true;
const level = Math.min(RAMP.length - 1, Math.floor((heat[i] * 0.85 + seed[i] * 0.3) * RAMP.length));
const ch = RAMP[level];
if (ch === " ") continue;
ctx.fillStyle = ink;
ctx.globalAlpha = heat[i] * strength;
ctx.fillText(ch, (i % cols) * CELL_W, Math.floor(i / cols) * CELL_H);
}
ctx.globalAlpha = 1;
raf = warm ? requestAnimationFrame(frame) : 0;
if (!warm) last = 0;
};
const move = (event: PointerEvent) => {
if (event.pointerType !== "mouse") return;
const box = canvas.getBoundingClientRect();
const x = event.clientX - box.left;
const y = event.clientY - box.top;
if (x < -radius || y < -radius || x > box.width + radius || y > box.height + radius) return;
const c0 = Math.max(0, Math.floor((x - radius) / CELL_W));
const c1 = Math.min(cols - 1, Math.ceil((x + radius) / CELL_W));
const r0 = Math.max(0, Math.floor((y - radius) / CELL_H));
const r1 = Math.min(rows - 1, Math.ceil((y + radius) / CELL_H));
for (let r = r0; r <= r1; r++) {
for (let c = c0; c <= c1; c++) {
const d = Math.hypot(c * CELL_W + CELL_W / 2 - x, r * CELL_H + CELL_H / 2 - y) / radius;
if (d >= 1) continue;
const i = r * cols + c;
heat[i] = Math.max(heat[i], (1 - d) * (1 - d));
}
}
if (!raf) raf = requestAnimationFrame(frame);
};
size();
const resize = new ResizeObserver(size);
if (page) window.addEventListener("resize", size);
else resize.observe(host);
const target: EventTarget = page ? window : host;
target.addEventListener("pointermove", move as EventListener);
return () => {
cancelAnimationFrame(raf);
resize.disconnect();
window.removeEventListener("resize", size);
target.removeEventListener("pointermove", move as EventListener);
};
}// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]
export function cn(...values: ClassValue[]): string {
const out: string[] = []
for (const v of values) {
if (!v) continue
if (Array.isArray(v)) {
const s = cn(...v)
if (s) out.push(s)
}
else out.push(v)
}
return out.join(' ')
}import { html, type PropertyValues } from 'lit'
import { DsElement, define } from '@/elements/lib/element'
import { whilePointerEffects } from '@/lib/effects/pointer'
import styles from 'virtual:tw'
// AsciiTrail.tsx as <spyglass-ascii-trail>: a mouse leaves a short trail of ASCII characters that fades in 700ms.
// `mode` section (absolute in the section around it; the page's classes size it) or page (fixed behind the page). Only
// for a fine pointer, 768 wide and up, without reduced motion. The host is the box. Decoration: aria-hidden.
/**
* @summary A fading ASCII trail behind the pointer.
*/
export class AsciiTrail extends DsElement {
static styles = [DsElement.styles, styles]
static properties = { mode: { reflect: true } }
/** section or page. */
mode: 'section' | 'page' = 'section'
private stop: (() => void) | null = null
private run = 0
connectedCallback() {
super.connectedCallback()
this.setAttribute('aria-hidden', 'true')
if (this.hasUpdated) this.start()
}
disconnectedCallback() {
super.disconnectedCallback()
this.halt()
}
private halt() {
this.run++
this.stop?.()
this.stop = null
}
private start() {
this.halt()
const canvas = this.renderRoot.querySelector('canvas')
if (!canvas) return
const mode = this.mode === 'page' ? 'page' : 'section'
const area = this.parentElement
this.stop = whilePointerEffects(() => import('@/lib/effects/ascii-trail').then(({ startTrail }) => startTrail(canvas, mode, area)))
}
protected updated(changed: PropertyValues) {
super.updated(changed)
if (changed.has('mode')) this.start()
}
render() {
return html`<canvas data-ascii-trail=${this.mode} class="block size-full text-fg"></canvas>`
}
}
define('ascii-trail', AsciiTrail)/* The host is the box, as AsciiTrail.tsx's canvas: absolute in its section (the page's classes size it), or fixed
behind the page in page mode. */
:host {
position: absolute;
display: block;
overflow: clip;
pointer-events: none;
}
:host([mode="page"]) {
position: fixed;
inset: 0;
z-index: -1;
width: 100%;
height: 100%;
}Reference: Site effect/AsciiTrail (AsciiTrail.tsx, trail.ts, AsciiTrail.module.css): 8 by 16 cells from " .:-=+*#", radius --ascii-trail-radius 72px, fade --ascii-trail-fade 700ms, opacity --ascii-trail-opacity 0.35; page mode fixed at z -1.