<bg-wc>

API Reference

Complete documentation for the <bg-wc> web component.

Install

npm

npm install @profpowell/bg-wc

Then import the element. The component self-registers as <bg-wc> on import.

import '@profpowell/bg-wc';

From source / CDN

<script type="module" src="https://unpkg.com/@profpowell/bg-wc"> </script>

Or vendor the src/ directory and reference it directly — it ships as plain ES modules with no build step.

Quick start

Drop the element on any page that defines the usual VB color tokens (--color-primary, --color-accent, …). The component reads them at frame time.

<bg-wc preset="mesh-gradient" intensity="0.65"> <h1>Hero headline</h1> <p>Content sits above the rendered layer in the light DOM.</p> <img slot="fallback" src="hero.webp" alt=""> </bg-wc>

Nothing required beyond the preset attribute. The fallback slot shows when prefers-reduced-motion: reduce is active and the chosen preset has no staticFrame().

data-background behavior

For pages that don't want to introduce a new custom element into their markup, import the optional data-background binder. It scans for elements with a data-background attribute and injects a <bg-wc> behind that element's content via z-index: -1 inside an isolated stacking context. The namespace is distinct from VB's data-effect, so the two can coexist on the same element.

import '@profpowell/bg-wc/data-background'; <section data-background="aurora" data-background-intensity="0.7" data-background-speed="0.3" data-background-color-1="#4dffa1"> <h1>Northern lights, behind anything.</h1> <p>Existing children stay put; bg-wc slides in behind.</p> </section>

Attribute mapping

data-background is the preset name. Any other key starting with data-background- maps to the corresponding bg-wc attribute — or, for color overrides, the corresponding --bg-wc-color-* custom property:

data-background-*Maps to
data-backgroundThe preset attribute. Required.
data-background-intensityintensity attribute
data-background-speedspeed
data-background-densitydensity
data-background-seedseed
data-background-palettepalette
data-background-qualityquality
data-background-fitfit
data-background-motionmotion
data-background-pausedpaused
data-background-pixel-ratiopixel-ratio
data-background-color-1--bg-wc-color-1 CSS var
data-background-color-2--bg-wc-color-2
data-background-color-3--bg-wc-color-3
data-background-color-bg--bg-wc-color-bg
data-background-color-fg--bg-wc-color-fg
data-background-skipPresence skips binding (escape hatch).

New elements added to the page after first paint are auto-bound via a MutationObserver. To bind manually after disabling that observer (or in an SSR context), call bindDataBackgrounds(root) after import.

Attributes

All attributes are observed; changes after first render are applied without re-init for cheap params, and trigger a renderer swap for preset.

AttributeType / valuesDefaultNotes
presetpreset nameRequired. See the catalog.
palette"theme" | "rainbow" | "mono""theme"Honored by particles most strongly.
intensity0..10.5Preset-specific "how dramatic" knob.
speed0..51Time multiplier. 0 freezes.
density0..10.5Particle count / shader detail.
seedinteger0Deterministic randomness. Useful for screenshots.
pausedbooleanunsetPauses the RAF loop without unmounting.
pixel-rationumbermin(devicePixelRatio, 2)Lower it for cheaper rendering on big screens.
quality"low" | "med" | "high""med"Renderer-level hint.
fit"cover" | "contain" | "stretch""cover"How the surface sizes inside the host.
motion"auto" | "reduce" | "force""auto"auto honors prefers-reduced-motion.
textstringPayload for text presets (crawl / marquee / sinescroll / cascade / source / wordcloud). Lines split on |. source treats the value as literal code and splits on newlines instead. Read fresh each frame.
modestringPreset-specific variant selector. mosaic: isometric, flat, sparse, stacked, blocks; doodles: family names; fly-through: space-delimited motion×profile×path×unit; explode: radial | cube. Changing it rebuilds css3d scenes. girih: 8fold/12fold/6fold; atomic: mixed/boomerangs/starbursts/harlequin; op-art: riley/cafewall/moire/drift. dotwork: rings/spiral/double/whorl/waterholes; stipple: field/contour/vortex.
use-themebooleanunsetUsed by system7; presence enables theme-token coloring instead of hard black/white.

Properties & methods

MemberTypeBehavior
.presetstringReflects the preset attribute.
.pausedbooleanReflects the paused attribute.
.pause()() => voidPauses the render loop.
.resume()() => voidResumes the render loop.
.snapshot()() => Promise<Blob>Returns a PNG snapshot of the current frame.
.readyPromise<void>Resolves when the active preset's first frame has rendered.
const el = document.querySelector('bg-wc'); await el.ready; const blob = await el.snapshot(); const url = URL.createObjectURL(blob); console.log('PNG ready:', url);

Events

EventDetailWhen
bg-wc:ready{ preset, renderer }First frame rendered.
bg-wc:preset-changed{ from, to }After a successful preset swap.
bg-wc:error{ phase, error }Compile, load, or runtime error. Element transitions to the fallback slot.
bg-wc:visibility{ visible: boolean }IntersectionObserver gate flipped.
el.addEventListener('bg-wc:ready', (e) => { console.log('preset:', e.detail.preset, 'renderer:', e.detail.renderer); });

CSS custom properties

Tokens are read once per frame via getComputedStyle() — theme switches reflect within one RAF tick without re-init.

Tokens the component reads

TokenUsed forFallback
--color-backgroundCanvas backdrop / clear colortransparent
--color-foregroundDefault particle / line color#1a1a1a
--color-primaryPrimary tint in shaders#3b82f6
--color-accentAccent tint#ec4899
--color-infoTertiary tint (mesh-gradient, aurora, …)#10b981
--color-successConfetti palette#22c55e
--color-warningConfetti palette#f59e0b
--color-errorConfetti palette#ef4444

Component-namespaced overrides

For when you want to feed a specific value without changing the global theme. Each one wins over the corresponding semantic token for that instance:

OverrideBeats
--bg-wc-color-1--color-primary
--bg-wc-color-2--color-accent
--bg-wc-color-3--color-info
--bg-wc-color-bg--color-background
--bg-wc-color-fg--color-foreground
--bg-wc-speedspeed attribute
--bg-wc-densitydensity
--bg-wc-intensityintensity
--bg-wc-pixel-ratiopixel-ratio
--bg-wc-z-indexInternal canvas stacking

Shadow parts

The internal <canvas> is exposed as part="canvas":

bg-wc::part(canvas) { image-rendering: pixelated; /* useful for the retro look */ filter: hue-rotate(20deg); }

Preset catalog

Each preset is its own dynamic import — loaded once on first use and cached. The kernel ships only the element class, the RAF loop, the renderer wrappers, and the token resolver.

WebGL shader presets

NameVisualTokens used
ditherAnimated halftone between two colorsprimary, accent
noiseDrifting fractal noise, two-color tintforeground, background
mesh-gradientStripe-style soft blob heroprimary, accent, info, background
halcyonEnormous soft color fields breathing into one another — the catalog's most restful entryprimary, accent, info, background
warpDisplacement-warped gridprimary, background
wavesFour sine-displaced color bandsprimary, accent, info, background
lavaMetaball lava lampprimary, accent, background
plasmaDemoscene plasma, sum of sinesprimary, accent, info
auroraVertical curtain noise + baseline ribbonprimary, accent, info, background
tunnelInfinite polar zoom with ring bandingprimary, accent, background
causticsWarped sin/cos fields for bright veinsprimary, accent, background
glitchRGB-shift datamosh with per-row displacementprimary, accent, background
rainbowFlowing spectral hue sweep (owns its palette)— (not theme-tinted)
halftoneRotated dot-grid halftone over an animated toneprimary, background
kaleidoscopeMirrored angular folds with a rotating patternprimary, accent, info
vhs80s analog video: wobble, chroma bleed, tracking noiseprimary, accent, background
synthwaveOutrun neon perspective grid + banded sunprimary, accent, info, background
crtCRT tube: barrel curve, scanlines, RGB phosphor maskprimary, accent, background
gameboy4-tone handheld with ordered dither + pixelationprimary, background
copperbarsAmiga demoscene metallic copper barsprimary, accent, info, background
topologyAnimated topographic contour linesprimary, accent, background
cellsAnimated Voronoi cells with darkened bordersprimary, accent, background
shineDiagonal sheen sweep over a quiet gradientprimary, accent, background
conicRotating angular gradient (spotlight border / loader)primary, accent, info, background
grainFilm-grain overlay; transparent, blend over content— (monochrome speckle)
trenchDeath Star trench run: square perspective corridorprimary, accent, background
marbleDomain-warped marble veins (mallsoft / luxe)primary, accent, background
metaballsDemoscene lava lamp — orbiting blobs merging at a soft iso surface, banded through three theme colorsprimary, accent, info, background
bendayPop-art Ben-Day dots over flat color blocksprimary, accent, info
comicPop-art radial action burst + shock ringsprimary, accent, info
decoArt-deco sunburst rays (Nagel / Gatsby)primary, accent, info, background
psychedeliaLiquid 1960s poster warp — melting concentric bands cycling three colors at full saturationprimary, accent, info, background
blissWindows-XP hills, sky, drifting cloudsprimary, info, background
moireTwo interfering ring fields drifting soft moiré bands (theme duotone)primary, accent, background
paper-grainWarm paper-fiber speckle, slow drift; blend over contentforeground (ink tint)

Vector / arcade presets (Canvas2D)

Glowing phosphor lines on a dark field — the Vectrex / arcade-vector look.

NameVisualTokens used
asteroidsDrifting, rotating wireframe rocksprimary, background
wireframeRotating wireframe globe + equatorial trenchprimary, accent, background
spirographAnimated hypotrochoid rosettesprimary, accent, info, background
incomingWireframe ships warping toward a turret crosshairprimary, accent, background
tempestTempest polygonal tube: spokes + receding ringsprimary, accent, info, background
fireworksVector fireball bursts (Star Wars arcade)primary, accent, info, semantic palette

Text presets (Canvas2D)

Type as the background. Set the copy with the text attribute; all but bootlog honor palette="rainbow|theme|mono". Presets in other groups also read text: source, wordcloud, ledticker, nixie, splitflap, neon-sign, and swarm — see their group tables.

NameVisualTokens used
crawlStar Wars-style perspective text crawlprimary, foreground, background
marqueeScrolling vector ticker (outline type)primary, accent, info, foreground
sinescrollDemoscene sine-wave scrollerprimary, accent, info, foreground
cascadeLetters drop & bounce in, hold, loopprimary, accent, info, foreground
bootlogScrolling boot / kernel log with [ OK ] and rare [FAIL] markerssuccess, error, foreground, background

Dataviz presets (Canvas2D)

Animated chart backgrounds — pair with an opaque content panel on top.

NameVisualTokens used
ledtickerDot-matrix LED marquee — scrolls text with a phosphor trail; a scrolling waveform without itaccent, warning, background
nixieRow of Nixie tubes ticking like a counter — warm wire digits with ghost stack and glass glow (reads text)accent, warning, foreground, background
splitflapSolari split-flap board clattering through messages on staggered cell schedules (reads text)warning, foreground, background
tradesTrading terminal: scrolling ticker columns + candlesprimary, success, error, foreground
dashboardStreaming area-line, bouncing bars, sweep gaugeprimary, accent, info, foreground
vectormapNode map with arcs + traveling packetsprimary, accent, info, foreground
transit-diagramBeck-style metro map — 45° routes, station ticks, interchange rings, trains running the linesprimary, accent, info, success, warning, foreground, background
scatterDrifting clusters of varied vector glyphsprimary, accent, info, foreground
waveformStacked waveform ridgelines (Joy-Division plot)primary, accent, background
wordcloudDrifting, breathing word cloud (reads text)primary, accent, info

Canvas2D particle presets

NameVisualTokens used
starsSlow-drifting starfield (parallax at intensity > 0.5)foreground, background
snowFalling flakes with horizontal driftforeground, background
rainLayered angled rainfall — depth-scaled streaks with splash ripples at the ground lineinfo, background
firefliesDusk glow-pulses wandering a gentle flow field; rare answering flies in accentwarning, accent, background
embersSparks rising off an unseen fire, cooling accent→primary as they climb over a warm bottom glowprimary, accent, background
constellationTwinkling star field with charted figures — star chains, join lines, a ringed catalog starprimary, accent, foreground, background
bubblesUnderwater column of wobbling rising bubbles under slow caustic light shaftsprimary, foreground, background
confettiContinuous drop in semantic paletteprimary, accent, success, warning, error
networkConnected-dots meshprimary, foreground
particlesGeneric drift — honors palette.per palette
pulseConcentric rings from centerprimary, accent, info
tetrisAmbient falling tetrominoesprimary, accent, info, success, warning, error
lanternsSky lanterns at dusk — warm flickering paper lights rising on swaying, depth-scaled pathswarning, accent, background
matrixFalling digital rain with glyph trailsprimary, foreground, background
mystifyWindows "Mystify" bouncing polyline screensaverprimary, accent, info, background

Canvas2D pattern & geometric presets

NameVisualTokens used
mosaic Refined squares. mode: isometric (default), flat, sparse, stacked, blocks. primary, accent, background
ribbons Bezier wave ribbons with crisp top-edge strokes. primary, accent, info, background
source Faded HTML source listing. Set text attribute to override with custom source. primary, foreground, background
system7 Drifting Mac windows on 50% stipple. Add use-theme to honor theme tokens; otherwise black-on-white. primary, background (when use-theme set)
atomic Mid-century atomic-age shapes — boomerangs, kidneys, starbursts. mode: mixed (default), boomerangs, starbursts, harlequin. primary, accent, info, background
stipple Pointillist dot fields. mode: field (default graded stipple), contour (dots trace a flow field), vortex (swirling, respawning). primary, accent, background
terrazzoSeeded stone-chip speckle in softened theme tints under a polish sheenprimary, accent, info, foreground, background
flowlines Thin streamlines fanning and converging through a slow-evolving flow field. primary, background
supergraphics Mural-scale curved bands — thick hard-edged stripes overlapping back-to-front (Sea Ranch supergraphics). primary, accent, info, background
doodles Hand-drawn marginalia sketching themselves in at the page edges, holding, then fading. mode: space/comma list of planner, botanical, geometric families (default all three). foreground
scandi Scandinavian grid of arc primitives and floral motifs in pastel-softened theme roles; tiles cross-fade slowly. primary, accent, info, success, warning, background
truchet Quarter-arc Truchet tiles flipped by a sweeping diagonal wavefront. mode: arcs (default), diagonals, wedges. primary, accent, background
delaunay Seeded triangulated mesh rippling on small point orbits; flat theme-mixed facets. primary, accent, info, background
hilbert Hilbert space-filling curve tracing itself — a bright head draws the trail, then the curve dissolves and redraws. primary, accent, info, background
groove 70s groovy stripe bundles snaking through rounded turns to a bullseye target; draw on, hold, retract. primary, accent, info, background
fan-decoErté scalloped shell-fans with radiating gold ribs in a staggered repeatprimary, accent, background
deco-spiresStepped-setback spires with lit window slits against wheeling gold raysprimary, accent, foreground, background
peacockA deco plume fan — gold ribs and barbs ending in concentric eyes, swaying as oneprimary, accent, info, background

Dimensional / CSS-3D presets

Built with DOM + CSS 3D transforms (the css3d renderer) rather than a canvas, so they compose with theme tokens and pause cleanly. Motion lives in CSS keyframes; snapshot() returns null for these. Use density to scale scene complexity and speed for tempo.

NameVisualTokens used
fly-through A rotating tunnel of theme-colored segments. mode composes space-delimited axes: motion orbit (default, rotates the whole tunnel in view) | fly (camera flies through it); profile ring (default) | corridor | hex | tube; path straight | helix | wave; unit cube | sphere | pyramid | card. palette="spectrum" for a rainbow instead of theme colors. primary, accent, info
carouselA rolodex ring of theme-gradient cards orbiting the camera, precessing slowlyprimary, accent, info, background
gyroscopeNested wireframe rings spinning on seeded axes around a pulsing coreprimary, accent, info, foreground
monolithDark slabs tumbling slowly over a floor grid, primary edge sheenprimary, foreground, background
shardsA rotating shell of translucent crystal fragments, each shimmering on its own cycleprimary, accent, info
cube-waveAn isometric board of real boxes bobbing in a wave radiating from centerprimary, background
skylineExtruded window-striped city blocks the camera pans past; a few accent-lit roofsprimary, accent, foreground, background
chamberInside a slowly rotating room of gradient walls with a drifting warm glowprimary, accent, warning, foreground, background
satellitesA disc-built planet with three tilted orbits carrying themed cardsprimary, accent, info, foreground, background
explode A field of particles over a floor grid that bursts outward and reassembles. mode: radial (default scatter) | cube (axis-aligned burst). seed fixes the scatter. primary, background, foreground

Atmospheric presets

NameVisualTokens used
nebula Deep-space gas — layered fbm clouds drifting at parallax rates over a bg→primary→accent ramp, pricked with star sparks and slow ignition flares. primary, accent, background
summit Mountain dawn — parallax noise ridgelines stepping back into a slow sunrise, with drifting mist bands and occasional birds. primary, accent, warning, background
lightningSeeded storm strikes on a t-derived schedule — branched bolts, sky flash, restless cloud glowaccent, foreground, background
fogThree parallax fbm banks drifting between bg and fg-tinted mist, thickening toward the horizonforeground, background
cumulusStacked rim-lit clouds drifting across a Parrish ultramarine-to-gold skyprimary, accent
moonriseA big low moon with halo, thin luminous cloud bands, a shimmering reflection columnprimary, foreground

Retro presets

NameVisualTokens used
equalizer 80s hi-fi graphic equalizer — LED segment columns thump to a synthesized spectrum with falling peak-hold caps. mode: bars (default), mirror, dots. success, warning, error, foreground, background
vumeter Analog VU meters — ballistic spring needles chase a synthesized signal past tick scales, a red zone, PEAK LEDs, and a sweeping glass glare. warning, error, foreground, background

Ornamental presets

NameVisualTokens used
girih Islamic periodic star-polygon strapwork lattice. mode: 8fold (default), 12fold, 6fold. primary, accent, info, background
mandala Layered concentric, counter-rotating radial symmetry; petal motifs keyed to ring, colors cycling outward. primary, accent, info, background
op-art Optical illusion with false motion. mode: riley (default), cafewall, moire, drift. foreground, background
dotwork Aboriginal/pointillist dot structures — concentric rosettes, spirals, whorls, songline waterholes. mode: rings (default), spiral, double, whorl, waterholes. primary, accent, background
tapestry Dense dot-art composite — a stippled field packed with rosettes and whorls; a rich backdrop for layered content. primary, accent, background
celtic-knotInterlaced strapwork plait with seeded turn-backs and a sliding glintprimary, accent, foreground, background
paisleyHalf-drop boteh block print, fill layer deliberately off-registerprimary, accent, info, background
azulejoQuadrant-symmetric glazed tiles with grout lines and a sweeping sheenprimary, accent, foreground, background
mudclothBogolanfini symbol bands, every stroke hand-jittered, slowly scrollingforeground, background
gildedKlimt-adjacent gold-leaf patchwork — spirals, squares, flecks shimmering patch by patchprimary, accent, warning, background

Japanese presets

NameVisualTokens used
seigaiha Overlapping scalloped wave-fan tiling — the classic blue-ocean pattern. primary, accent, info, background
sumi-e Ink-wash blooms diffusing into paper — bokashi bleed and granulation on staggered grow/fade cycles. foreground, primary, background
kintsugi Gold crack veins growing, branching, and shimmering across a dark slab; the network reseeds each cycle. warning, accent, background
ukiyo-e Woodblock-print waves — flat-color parallax layers with outlined crests and curling foam claws under a bokashi sky. primary, info, foreground, background
sakura Cherry petals tumbling through three depth layers on gusting wind. primary, background
origami Sheets fold into figures via hand-authored crease scripts with pseudo-3D foreshortening — guides draw first, the form folds step by step, holds, then fades. primary, accent, info, foreground, background
zen-gardenRaked karesansui sand — breathing rake field, stones, combed concentric furrowsforeground, background

Print art presets

NameVisualTokens used
risograph Two-ink riso overprint — misregistered blobs and bars multiplying into a third color, with heavy per-ink grain and dropouts. primary, accent, background
plotter Pen-plotter art drawing itself — flow fields, hatched discs, and contour stacks revealed stroke by stroke with a visible pen head. foreground, primary, background
linocut Carved-block shapes with rough edges and gouge marks, rolling slowly like a print cylinder. primary, accent, foreground, background
cyanotypeBotanical sun prints — fern and seed-head silhouettes glowing on Prussian-tinted primaryprimary, foreground
screenprintThree off-register ink pulls per motif, multiplied where they overlap, one through a halftone screenprimary, accent, info, background

Classic presets

NameVisualTokens used
alchemy Engraved esoteric diagram — nested rings of invented sigils, inscribed polygons, and seeded chords etch on, each ring rotating at its own slow rate. foreground, accent, background
bauhaus Grid composition of primary geometric forms (circles, arcs, triangles, bars) at full saturation; cells slide into place and recompose on staggered cycles. primary, accent, info, success, warning, error
cave Parietal cave art — charcoal animal outlines and ochre handprint stencils emerge from a mottled rock wall under a drifting torchlight vignette. foreground, warning, error, background
clockwork Meshing brass gear train — ratio-locked gears with trapezoid teeth, phase-aligned at their contact points, plus a ticking escapement wheel. warning, accent, background
damask Procedural damask tile — mirrored flourish motif under a slow diagonal specular sheen. primary, accent, background
de-stijl Mondrian composition from recursive seeded splits; rule lines periodically redraw, coloured cells cross-fade. primary, accent, info, foreground, background
hieroglyph Columns of invented glyph forms (eye, bird, wave, reed, sun…) chisel in top-to-bottom on a speckled sandstone field, with an inset shadow so they read as carved. foreground, warning, background
illuminated Manuscript page — a gilded initial capital swept by an animated sheen, vine marginalia growing down the margin, and rubricated line stubs on parchment. primary, success, warning, error, foreground, background
meander Greek-key fret rows scrolling in alternating directions with per-row parallax. primary, accent, background
morris Morris-style wallpaper — mirrored acanthus/vine tiles that draw themselves on, then breathe; pastel-softened theme roles. primary, accent, info, background
art-nouveauWhiplash-curve vines with leaves and buds inside a double frame; tendril tips swayprimary, accent, foreground, background
constructivismLissitzky field — a dominant diagonal wedge and floating planes drifting on a rotated axisprimary, accent, info, foreground, background
stained-glass Gothic window — seeded Voronoi panes between thick dark lead cames, each tinted by hashed theme roles, with a slow light bloom drifting behind the glass. primary, accent, info, success, warning, background
swiss International Typographic Style — a strict modular grid carries oversized numerals, thick rules, and flat colour planes sliding between seeded alignments, one element at a time. primary, accent, error, foreground, background

Art presets

NameVisualTokens used
colorfield Colour-field abstraction — stacked soft-edged rectangles of colour with grain-roughened smoothstep edges, breathing glacially over a toned ground. primary, accent, info, background
cutouts Paper-cut collage — organic silhouettes (fronds, leaves, rounded stars, seed forms) drift and layer like physically placed cut paper with a slight drop offset. primary, accent, info, success, warning, error, background
drip Action painting — flung-paint spline arcs and droplet spatter accumulate Pollock-style on a canvas weave; a slow whitewash veils and restarts when coverage saturates. primary, accent, info, warning, error, foreground, background
graffiti Spray writing — seeded tags build dab by dab with a dense core, wide overspray, and descending drip runs on a concrete wall, fading behind newer layers. primary, accent, info, warning, error, foreground, background
mobile Kinetic hanging sculpture — a seeded binary tree of wire arms and coloured paddles swinging as coupled damped pendulums, kept alive by gentle periodic impulses. primary, accent, info, warning, error, foreground, background
watercolor Wet-on-wet blooms — fbm-edged splats glaze multiplicatively with a darker granulated wet-edge band bleeding into paper grain; washes grow, hold, then fade. primary, accent, info, success, warning, background
brushstrokeImpasto flow field — directional ribbon strokes with painted highlights swirling around seeded centersprimary, accent, info, background
terraceClassical column and urn silhouettes framing a breathing luminous skyprimary, accent, foreground
oil-skyA skyscape of visible oil dabs — warm horizon rising through banded brushwork to cool zenithprimary, accent

Kitsch presets

NameVisualTokens used
crochet Granny-square afghan — squares crochet themselves stitch by stitch, round by round, yarn colour rotating through theme roles in the classic scrap-yarn look. primary, accent, info, success, warning, foreground, background
disco Mirror-ball light — a perspective grid of parallelogram light cells sweeps a dark floor-and-wall space, tint-cycling through theme roles with occasional lens-flare pings. primary, accent, info, background
domino Domino chains seen from above — a toppling wave travels seeded curved paths, tiles laying flat over their leading edges while the chain quietly re-stands behind the front. primary, accent, info, foreground, background
neon-sign Roadside neon — tube-outline shapes and a tube-script word (“OPEN”, or set text) with bulb-chase dots, per-segment flicker, and pre-rendered glow. primary, accent, info, warning, background
pegboard Backlit toy peg board — glowing translucent pegs fill in seeded pictures (star, heart, rocket, rainbow) peg by peg, hold lit, then clear for the next. primary, accent, info, success, warning, background
quilt Patchwork — classic quilt blocks (log cabin, flying geese, pinwheel, nine-patch) assemble patch by patch under a fabric-grain overlay, occasionally re-piecing themselves. primary, accent, info, warning, error, foreground, background

Science presets

NameVisualTokens used
phyllotaxis Golden-angle spiral (Vogel model) — dots emitted from the centre age outward, colour cycling by ring band. primary, accent, info, background
boids Reynolds flocking — tapered streaks steered by separation / alignment / cohesion, coloured by speed. primary, foreground, background
helix DNA-style double helix — depth-sorted strands and base-pair rungs scrolling along the axis. primary, accent, foreground, background
mycelium Branching filament growth accumulating into a network; restarts with a fresh palette rotation when coverage saturates. primary, accent, info, background
reaction-diffusion Gray-Scott reaction-diffusion; density selects a spots / stripes / coral / waves regime. primary, accent, background
chladni Vibrating Chladni plate — sand gathers on nodal lines as the mode pair cross-fades. primary, accent, background
orbital Planetary system — satellites ride seeded ellipses with true Keplerian speed variation, trailing faded orbit arcs; occasional Hohmann-style transfers animate between orbits. primary, accent, info, success, warning, foreground, background
slime-mold Physarum agents depositing and chasing a diffusing trail (needs renderable float textures; degrades to a frozen field). primary, accent, background

Tech presets

NameVisualTokens used
circuit PCB traces routed on a 45° grid with pads, vias, and IC footprints; bright signal pulses travel the traces. primary, accent, foreground, background
blueprint Drafting on blue grid paper — outlines, centrelines, and dimension lines draw on, hold, then fade. primary, info, foreground, background
radar PPI radar scope — rotating sweep with phosphor persistence; seeded blips flare and fade. primary, accent, background
gyroid Raymarched gyroid minimal surface slowly rotating through the lattice, lit with two theme colours against a bg fog. primary, accent, background
lidar Terrain point cloud revealed by a scanning plane; points flare on the scan line and stay dimly lit behind it. primary, accent, background
oscilloscope Lissajous / waveform traces with glowing phosphor-persistence trails. primary, accent, info, background
spectrum Spectrum analyzer — a live FFT bar strip feeds a scrolling time-frequency waterfall below; magnitudes ramp through bg→primary→accent→warning. primary, accent, warning, background
hologram Projected wireframe — an icosahedron and a torus knot alternate rotating above a projector glow, drawn as scan-lined emissive lines with a chromatic ghost and occasional frame tears. primary, accent, background
neon-city Night skyline over wet asphalt — lit-window towers and saturated neon signs mirrored in a rain-slick, streak-blurred, ripple-perturbed street. primary, accent, info, background
swarm Drone light show — hundreds of glowing points fly formation transitions (scatter, ring, lattice, figures); lines of text rasterize into formations. primary, accent, background

Nature presets

NameVisualTokens used
komorebi Dappled late-afternoon light through swaying trees — warm sunflecks drift and breathe over a layered foliage shadow, with long raking light shafts. success, warning, accent, background
leavesAutumn leaves in three shapes tumbling down swaying paths, leaning together under a slow gustprimary, accent, warning, background
migration Birds migrating high in an autumn sky — undulating V-skeins at parallax altitudes, lead birds trading off, far skeins smaller and paler. accent, info, warning, foreground, background
palms Palm trees swaying against a tropical sky, distant palms hazier (parallax). mode: silhouette (default, sunset), lit (daytime). primary, accent, info, success, warning, foreground, background
reeds Cattails and tall grasses swaying as travelling wind gusts sweep across, in 2–3 depth layers with pastel-softened backs. primary, info, success, warning, background
lily-pondMonet water — vertical reflection smears, drifting pads, slow ripple ringsprimary, accent, info, success, foreground, background
meadowDusk grassland in three swaying parallax layers, seed heads catching lightprimary, accent, warning, foreground, background
tideA breathing shoreline — translucent wave sheets advancing over sand with foam edgesinfo, warning, background

Lounge presets

NameVisualTokens used
barkcloth 1950s tiki / Hawaiian barkcloth textile — stylized tropical motifs (monstera, hibiscus, fronds) on a brick-offset tile grid, drifting like fabric stirring in a breeze. primary, accent, info, success, warning, foreground, background
breezeblock Atomic-ranch decorative concrete screen — geometric apertures backlit by a raking diagonal light sweep, with a floating starburst. mode: hourglass, circle, leaf, mixed. primary, accent, warning, foreground, background
lanai Mid-century pool patio — a kidney pool with caustic ripples on a terrazzo deck, amoeba stepping stones, a starburst sun, and swaying palm-frond shadows. primary, accent, info, warning, background
tiki Torch-lit tiki bar at night — carved totem silhouettes flanked by flickering torches, hanging glass-float lamps, and a thatch eave over a deep tropical-night gradient. primary, accent, info, warning, foreground, background

Music presets

NameVisualTokens used
liquid-lightOil-projection dye blobs swirling on a warped field, blooming to white where they overlapprimary, accent, info, background
bluenoteReid Miles jazz sleeve — duotone tone blocks, thick rules, oversized dot row; one block slidesprimary, accent, foreground, background
starburstFunk ray burst — concentric counter-rotating spoke rings around a hot coreprimary, accent, warning, background
vinylA spinning record — grooves and rotating label under a fixed light sheenprimary, accent, foreground, background
prismA beam refracting through a prism into a six-band spectrum fan; the entry angle driftsprimary, accent, info, success, warning, foreground, background
laser-showLaserium beam fans sweeping lissajous paths through hazeprimary, accent, info, background
scanimateAnalog ident sweeps — glowing ribbon curves drawing themselves across the frameprimary, accent, info, background
airbrushProg-sleeve gatefold — soft gradient orbs, a horizon belt, and sweeping arcs adriftprimary, accent, info, background
video-feedbackCamera-at-monitor recursion — nested spinning frames tinted primary→accent→infoprimary, accent, info, background
stage-lightsPar-can cones sweeping colored beams through haze over a stage edgeprimary, accent, info, foreground, background
chromeAirbrushed 80s logo metal — mirrored banded horizon with a traveling specular sweepprimary, background

Reduced motion

prefers-reduced-motion: reduce triggers the same code path as motion="reduce" on the element:

  1. If nothing is renderable (no preset loaded, a failed load, or a lost context) → show the fallback slot, regardless of motion settings.
  2. Else if the preset is css3d → keep the paused scene visible; the slot never swaps in.
  3. Else if the preset declares a staticFrame() method → render one still frame and halt the RAF loop. The static frame wins even when the fallback slot has content.
  4. Else → hide the canvas and show the fallback slot.

Every canvas preset ships staticFrame(); css3d presets show their paused scene instead.

Performance

Many instances on one page

Browsers cap simultaneous WebGL contexts (commonly ~16). Each shader-preset <bg-wc> holds one context, so a page that mounts more than that at once (a full catalog grid, a poster wall) will see the browser drop the oldest contexts. Canvas2D presets are not affected.

Two ways to stay under the cap:

import { listGroups } from '@profpowell/bg-wc/presets/index'; for (const { id, label, presets } of listGroups()) { console.log(label, presets.map(p => p.name)); } // Gradients ['ribbons','flowlines','mesh-gradient','waves','plasma','rainbow','shine','conic'] // Geometric ['mosaic','supergraphics','warp','topology','cells','kaleidoscope','doodles','scandi', /* … */] // Texture ['dither','halftone','grain','paper-grain','stipple'] // …

Recipes

Halftone overlay on flat shapes

<div class="poster"> <svg class="shapes">...</svg> <bg-wc preset="noise" intensity="0.7" style="position:absolute; inset:0; mix-blend-mode:multiply; opacity:0.18; --bg-wc-color-fg:#000; --bg-wc-color-bg:#fff;"> </bg-wc> </div>

Two layered presets (aurora behind stars)

<div class="sky"> <bg-wc preset="aurora"></bg-wc> <bg-wc preset="stars" style="--bg-wc-color-bg: transparent;"></bg-wc> </div>

The top layer must declare a transparent background or its Canvas2D clearRect + bg-fill will mask the layer below.

Section background via data-background

<section data-background="caustics" data-background-intensity="0.8" data-background-density="0.45" data-background-speed="0.55"> <h1>Six metres down.</h1> </section>

Hot-swap presets at runtime

el.setAttribute('preset', 'plasma'); await el.ready; // resolves once the new preset's first frame renders console.log(el.preset); // 'plasma'

Snapshot to file

const blob = await el.snapshot(); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `${el.preset}.png`; a.click();

Conic spotlight border

Put a conic behind a panel inset by a hair; only the rim shows, so the border sweeps with light. No @property shim required.

<div class="glow-card"> <bg-wc preset="conic" speed="1.6"></bg-wc> <div class="inner">Card content</div> </div> <style> .glow-card { position: relative; border-radius: 18px; padding: 1.5px; overflow: hidden; isolation: isolate; } .glow-card > bg-wc { position: absolute; inset: -60%; z-index: 0; } /* oversize so corners stay covered */ .glow-card .inner { position: relative; z-index: 1; background: var(--surface); border-radius: 16.5px; padding: 28px; } </style>

Scroll-linked background

The component re-reads --bg-wc-intensity / --bg-wc-speed (and color tokens) every frame, so driving them from a scroll handler is all it takes.

const hero = document.querySelector('bg-wc'); addEventListener('scroll', () => { const p = Math.min(1, scrollY / innerHeight); hero.style.setProperty('--bg-wc-intensity', (0.45 + p * 0.5).toFixed(3)); hero.style.filter = `hue-rotate(${Math.round(p * 80)}deg)`; }, { passive: true });

Whole-page film grain

<bg-wc preset="grain" intensity="0.5" style="position:fixed; inset:0; z-index:100; pointer-events:none; mix-blend-mode:soft-light; opacity:0.6;"> </bg-wc>

Browser support

Targets Chromium, Firefox, and Safari at current stable versions. Requires WebGL1 (universally available) for shader presets; Canvas2D presets work anywhere a custom element is registered.

Optional features and their graceful degradations:

FeatureFallback if unavailable
WebGL2WebGL1 context attempted automatically.
OffscreenCanvasMain-thread rendering. No behavioral change.
navigator.getBattery()Battery-aware pause is skipped.
backdrop-filterGlass effects in some demos lose blur; layout intact.
ElementInternals.states:focus-within child-focus state is skipped.