Overview
Components
Text Animations
A seeded avatar canvas that renders a deterministic color composition with hover-only animation and a built-in 2D fallback.
xxtomm
svelte
neo
Aidan
dheeraj
preview.svelte
<script lang="ts"> import { FallbackAvatar } from "$lib/components/spell/fallback-avatar/index.js";
const names = ["xxtomm", "svelte", "neo", "Aidan", "dheeraj"];</script>
<div class="flex flex-wrap items-center gap-3"> {#each names as name} <div class="flex flex-col items-center gap-1"> <FallbackAvatar class="border" {name} size={32} /> <span class="text-muted-foreground text-[11px]">{name}</span> </div> {/each}</div>Installation
pnpm dlx shadcn-svelte@latest add https://sv-animations.vercel.app/s/fallback-avatar.json
Copy the Source Code
Copy and paste the following code into your project:
fallback-avatar.svelte
<script lang="ts"> import { browser } from "$app/env"; import { cn, type WithoutChildren } from "#lib/utils.js"; import { onMount } from "svelte"; import type { ClassValue, HTMLAttributes } from "svelte/elements";
import type { Uniforms } from "./utils"; import { computeUniforms } from "./utils"; import { renderFallback2D, renderWebGLToCanvas } from "./webgl";
type Props = WithoutChildren< Omit<HTMLAttributes<HTMLCanvasElement>, "class" | "children" | "width" | "height"> > & { name: string; size?: number; animated?: boolean; class?: ClassValue; style?: string; };
let { name, size = 32, animated = true, class: className, style, ...restProps }: Props = $props();
let canvas = $state<HTMLCanvasElement | null>(null);
let rafId: number | null = null; let isHovering = false; let animationTime = 0; let hoverStartTimestamp: number | null = null; let uniformsCache: Uniforms | null = null; let shouldUse2DFallback = false;
const rootStyle = $derived( [style ? String(style) : "", "display: block", `width: ${size}px`, `height: ${size}px`] .filter(Boolean) .join("; ") );
function getUniforms() { if (!uniformsCache) { uniformsCache = computeUniforms(name); }
return uniformsCache; }
// The canvas bitmap is scaled with DPR while the CSS box stays tied to the `size` prop. function syncCanvasResolution() { if (!browser) return;
const nextPixelSize = Math.max(1, Math.round(size * (window.devicePixelRatio || 1)));
if (canvas) { canvas.width = nextPixelSize; canvas.height = nextPixelSize; } }
function stopAnimation() { if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
hoverStartTimestamp = null; }
function draw(time: number) { if (!canvas) return;
const uniforms = getUniforms();
if (!shouldUse2DFallback) { const renderedWithWebGL = renderWebGLToCanvas(canvas, uniforms, time); if (renderedWithWebGL) { return; }
shouldUse2DFallback = true; }
renderFallback2D(canvas, uniforms, time); }
// Hover animation keeps elapsed time so leaving and re-entering continues from the last frame. function animate(timestamp: number) { if (!isHovering) { stopAnimation(); return; }
if (hoverStartTimestamp === null) { hoverStartTimestamp = timestamp - animationTime * 1000; }
animationTime = (timestamp - hoverStartTimestamp) / 1000; draw(animationTime); rafId = requestAnimationFrame(animate); }
function handlePointerEnter() { if (!animated || !canvas || isHovering) return;
isHovering = true; hoverStartTimestamp = null; rafId = requestAnimationFrame(animate); }
function handlePointerLeave() { if (!canvas) return;
isHovering = false; stopAnimation(); draw(animationTime); }
onMount(() => { syncCanvasResolution(); draw(0);
return () => { isHovering = false; stopAnimation(); }; });
$effect(() => { name;
if (!browser || !canvas) return;
uniformsCache = null; animationTime = 0; isHovering = false; stopAnimation(); syncCanvasResolution(); draw(0); });
$effect(() => { size;
if (!browser || !canvas) return;
syncCanvasResolution(); draw(animationTime); });
$effect(() => { animated;
if (!animated) { isHovering = false; stopAnimation();
if (browser && canvas) { draw(animationTime); } } });</script>
<canvas bind:this={canvas} data-slot="fallback-avatar" width={size} height={size} class={cn("rounded-full", className)} style={rootStyle} onpointerenter={handlePointerEnter} onpointerleave={handlePointerLeave} {...restProps}></canvas> index.ts
import FallbackAvatar from "./fallback-avatar.svelte";export { FallbackAvatar }; utils.ts
export type RGBColor = [number, number, number];
export interface Uniforms { S: number; H: number; P: [number, number, number, number]; Q: [number, number, number, number]; C1: [number, number, number]; C2: [number, number, number];}
export function hashString(value: string): [number, number] { let h1 = 0xdeadbeef; let h2 = 0x41c6ce57;
for (let index = 0; index < value.length; index += 1) { const charCode = value.charCodeAt(index); h1 = Math.imul(h1 ^ charCode, 2654435761); h2 = Math.imul(h2 ^ charCode, 1597334677); }
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507); h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909); h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507); h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return [h1 >>> 0, h2 >>> 0];}
export function mulberry32(seed: number) { return () => { seed |= 0; 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; };}
export function deriveHue(hash: [number, number]): number { const bytes: number[] = [];
for (let index = 0; index < 4; index += 1) { bytes.push((hash[0] >> (index * 8)) & 0xff); bytes.push((hash[1] >> (index * 8)) & 0xff); }
return bytes.reduce((sum, byte) => sum + byte, 0) % 360;}
export function oklchToRgb(lightness: number, chroma: number, hue: number): RGBColor { const radians = (hue * Math.PI) / 180; const a = chroma * Math.cos(radians); const b = chroma * Math.sin(radians); const lPrime = lightness + 0.3963377774 * a + 0.2158037573 * b; const mPrime = lightness - 0.1055613458 * a - 0.0638541728 * b; const sPrime = lightness - 0.0894841775 * a - 1.291485548 * b; const l = lPrime * lPrime * lPrime; const m = mPrime * mPrime * mPrime; const s = sPrime * sPrime * sPrime;
const red = +4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s; const green = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s; const blue = -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s;
const gammaCorrect = (channel: number) => channel <= 0.0031308 ? 12.92 * channel : 1.055 * Math.pow(channel, 1 / 2.4) - 0.055;
return [ Math.round(Math.max(0, Math.min(1, gammaCorrect(red))) * 255), Math.round(Math.max(0, Math.min(1, gammaCorrect(green))) * 255), Math.round(Math.max(0, Math.min(1, gammaCorrect(blue))) * 255), ];}
export function getColors(hash: [number, number]): [RGBColor, RGBColor] { const hue = deriveHue(hash); return [oklchToRgb(0.8, 0.18, hue), oklchToRgb(0.45, 0.18, hue)];}
// We derive every visual input from the same name seed so the avatar is stable across reloads.export function computeUniforms(name: string): Uniforms { const hash = hashString(name); const random = mulberry32(hash[0]); const [colorOne, colorTwo] = getColors(hash); const points: number[] = [];
for (let index = 0; index < 8; index += 1) { points.push(random()); }
return { S: hash[0] / 4294967296, H: deriveHue(hash) / 360, P: [points[0], points[1], points[2], points[3]], Q: [points[4], points[5], points[6], points[7]], C1: [colorOne[0] / 255, colorOne[1] / 255, colorOne[2] / 255], C2: [colorTwo[0] / 255, colorTwo[1] / 255, colorTwo[2] / 255], };} webgl.ts
import type { RGBColor, Uniforms } from "./utils";
const VERT_SRC = "attribute vec2 a;void main(){gl_Position=vec4(a,0,1);}";
const FRAG_SRC = `precision mediump float;uniform vec2 R;uniform float S,H;uniform vec4 P,Q;uniform vec3 C1,C2;uniform float T;#define UV (gl_FragCoord.xy/R)
void main(){ vec2 uv=UV; vec2 b1=vec2(P.x,P.y); vec2 b2=vec2(P.z,P.w); vec2 b3=vec2(Q.x,Q.y); vec2 c1=b1+vec2(sin(T*.7+b1.x*6.)*.08, cos(T*.9+b1.y*6.)*.08); vec2 c2=b2+vec2(sin(T*.6+2.1)*.1, cos(T*.8+1.3)*.07); vec2 c3=b3+vec2(sin(T*.5+4.2)*.07, cos(T*1.1+3.7)*.09); float breath=1.+sin(T*1.3)*.06; float d1=(1.-length(uv-c1)*1.5)*breath; float d2=(1.-length(uv-c2)*1.5)*(1.+sin(T*1.7+1.)*.05); float d3=(1.-length(uv-c3)*1.5)*(1.+sin(T*1.1+2.)*.05); vec3 col=vec3(0); col=1.-(1.-col)*(1.-C1*max(d1,0.)); col=1.-(1.-col)*(1.-C2*max(d2,0.)); vec3 c3col=mix(C1,C2,.5+sin(T*.4)*.15); col=1.-(1.-col)*(1.-c3col*max(d3,0.)); col=clamp(col,0.,1.); gl_FragColor=vec4(col,1);}`;
interface WebGLRenderer { gl: WebGLRenderingContext; canvas: HTMLCanvasElement; program: WebGLProgram; vertexBuffer: WebGLBuffer; positionAttribute: number; resolutionUniform: WebGLUniformLocation | null; seedUniform: WebGLUniformLocation | null; hueUniform: WebGLUniformLocation | null; pointsPUniform: WebGLUniformLocation | null; pointsQUniform: WebGLUniformLocation | null; colorOneUniform: WebGLUniformLocation | null; colorTwoUniform: WebGLUniformLocation | null; timeUniform: WebGLUniformLocation | null;}
let cachedRenderer: WebGLRenderer | null = null;let rendererInitAttempted = false;
function compileShader( gl: WebGLRenderingContext, type: number, source: string): WebGLShader | null { const shader = gl.createShader(type); if (!shader) return null;
gl.shaderSource(shader, source); gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { gl.deleteShader(shader); return null; }
return shader;}
function createProgram( gl: WebGLRenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader): WebGLProgram | null { const program = gl.createProgram(); if (!program) return null;
gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { gl.deleteProgram(program); return null; }
return program;}
// The GL program is cached at module scope so multiple avatars reuse one tiny renderer.export function ensureWebGLRenderer(): WebGLRenderer | null { if (rendererInitAttempted) { return cachedRenderer; }
rendererInitAttempted = true;
if (typeof document === "undefined") { return null; }
const canvas = document.createElement("canvas"); canvas.width = 64; canvas.height = 64;
const gl = canvas.getContext("webgl", { antialias: false, depth: false, preserveDrawingBuffer: true, });
if (!gl) { return null; }
const vertexShader = compileShader(gl, gl.VERTEX_SHADER, VERT_SRC); const fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, FRAG_SRC);
if (!vertexShader || !fragmentShader) { if (vertexShader) gl.deleteShader(vertexShader); if (fragmentShader) gl.deleteShader(fragmentShader); return null; }
const program = createProgram(gl, vertexShader, fragmentShader); gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader);
if (!program) { return null; }
const vertexBuffer = gl.createBuffer(); if (!vertexBuffer) { gl.deleteProgram(program); return null; }
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]), gl.STATIC_DRAW );
const positionAttribute = gl.getAttribLocation(program, "a");
if (positionAttribute < 0) { gl.deleteBuffer(vertexBuffer); gl.deleteProgram(program); return null; }
cachedRenderer = { gl, canvas, program, vertexBuffer, positionAttribute, resolutionUniform: gl.getUniformLocation(program, "R"), seedUniform: gl.getUniformLocation(program, "S"), hueUniform: gl.getUniformLocation(program, "H"), pointsPUniform: gl.getUniformLocation(program, "P"), pointsQUniform: gl.getUniformLocation(program, "Q"), colorOneUniform: gl.getUniformLocation(program, "C1"), colorTwoUniform: gl.getUniformLocation(program, "C2"), timeUniform: gl.getUniformLocation(program, "T"), };
return cachedRenderer;}
export function renderWebGLToCanvas( targetCanvas: HTMLCanvasElement, uniforms: Uniforms, time: number): boolean { const renderer = ensureWebGLRenderer(); if (!renderer) { return false; }
const { gl, canvas, program, vertexBuffer } = renderer; const width = Math.max(1, targetCanvas.width); const height = Math.max(1, targetCanvas.height);
if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; }
gl.viewport(0, 0, width, height); gl.useProgram(program); gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer); gl.enableVertexAttribArray(renderer.positionAttribute); gl.vertexAttribPointer(renderer.positionAttribute, 2, gl.FLOAT, false, 0, 0); gl.uniform2f(renderer.resolutionUniform, width, height); gl.uniform1f(renderer.seedUniform, uniforms.S); gl.uniform1f(renderer.hueUniform, uniforms.H); gl.uniform4fv(renderer.pointsPUniform, uniforms.P); gl.uniform4fv(renderer.pointsQUniform, uniforms.Q); gl.uniform3fv(renderer.colorOneUniform, uniforms.C1); gl.uniform3fv(renderer.colorTwoUniform, uniforms.C2); gl.uniform1f(renderer.timeUniform, time); gl.drawArrays(gl.TRIANGLES, 0, 6);
const context = targetCanvas.getContext("2d"); if (!context) { return false; }
context.clearRect(0, 0, width, height); context.drawImage(canvas, 0, 0);
return true;}
function toRgbString(color: RGBColor, alpha: number) { return `rgba(${color[0]}, ${color[1]}, ${color[2]}, ${alpha})`;}
function colorFromUniform(uniformColor: Uniforms["C1"] | Uniforms["C2"]): RGBColor { return [ Math.round(uniformColor[0] * 255), Math.round(uniformColor[1] * 255), Math.round(uniformColor[2] * 255), ];}
function mixColor(first: RGBColor, second: RGBColor, ratio: number): RGBColor { return [ Math.round(first[0] + (second[0] - first[0]) * ratio), Math.round(first[1] + (second[1] - first[1]) * ratio), Math.round(first[2] + (second[2] - first[2]) * ratio), ];}
function blobCenters(uniforms: Uniforms, time: number) { const baseOne = { x: uniforms.P[0], y: uniforms.P[1] }; const baseTwo = { x: uniforms.P[2], y: uniforms.P[3] }; const baseThree = { x: uniforms.Q[0], y: uniforms.Q[1] };
return [ { x: baseOne.x + Math.sin(time * 0.7 + baseOne.x * 6) * 0.08, y: baseOne.y + Math.cos(time * 0.9 + baseOne.y * 6) * 0.08, }, { x: baseTwo.x + Math.sin(time * 0.6 + 2.1) * 0.1, y: baseTwo.y + Math.cos(time * 0.8 + 1.3) * 0.07, }, { x: baseThree.x + Math.sin(time * 0.5 + 4.2) * 0.07, y: baseThree.y + Math.cos(time * 1.1 + 3.7) * 0.09, }, ] as const;}
function drawBlob( context: CanvasRenderingContext2D, centerX: number, centerY: number, radius: number, color: RGBColor, alpha: number) { const gradient = context.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius); gradient.addColorStop(0, toRgbString(color, alpha)); gradient.addColorStop(0.45, toRgbString(color, alpha * 0.55)); gradient.addColorStop(1, toRgbString(color, 0));
context.fillStyle = gradient; context.beginPath(); context.arc(centerX, centerY, radius, 0, Math.PI * 2); context.fill();}
// The fallback keeps the same seeded colors and point layout so the avatar stays recognizable.export function renderFallback2D( targetCanvas: HTMLCanvasElement, uniforms: Uniforms, time = 0): boolean { const context = targetCanvas.getContext("2d"); if (!context) { return false; }
const width = Math.max(1, targetCanvas.width); const height = Math.max(1, targetCanvas.height); const radius = Math.max(width, height) * 0.55; const primary = colorFromUniform(uniforms.C1); const secondary = colorFromUniform(uniforms.C2); const tertiary = mixColor(primary, secondary, 0.5 + Math.sin(time * 0.4) * 0.15); const [centerOne, centerTwo, centerThree] = blobCenters(uniforms, time);
context.clearRect(0, 0, width, height); context.fillStyle = "rgb(0, 0, 0)"; context.fillRect(0, 0, width, height); context.globalCompositeOperation = "screen";
drawBlob(context, centerOne.x * width, centerOne.y * height, radius, primary, 0.92); drawBlob(context, centerTwo.x * width, centerTwo.y * height, radius, secondary, 0.88); drawBlob(context, centerThree.x * width, centerThree.y * height, radius, tertiary, 0.84);
context.globalCompositeOperation = "source-over";
return true;}Folder Structure
Folder Structure
src/└── lib/ └── components/ └── spell/ └── fallback-avatar/ ├── fallback-avatar.svelte ├── index.ts ├── utils.ts └── webgl.tsInstall and integrate the Svelte component documented below.https://sv-animations.vercel.app/spell/fallback-avatar/llms.txt
Follow the guide's installation and usage instructions.Match the project's existing structure, imports, and styles.Keep changes scoped to the component and verify it works.Reply with a short bullet list of completed changes.Usage
<script lang="ts"> import { FallbackAvatar } from "#lib/components/spell/fallback-avatar/index.js";</script>
<FallbackAvatar name="Svelte" />Examples
Size
Use the same seeded avatar across multiple size values when you need tiny inline chips, default profile dots, or larger hero accents.
20px
28px
36px
44px
size-example.svelte
<script lang="ts"> import { FallbackAvatar } from "$lib/components/spell/fallback-avatar/index.js";
const sizes = [20, 28, 36, 44] as const;</script>
<div class="flex items-end gap-6"> {#each sizes as size} <div class="flex flex-col items-center gap-3"> <FallbackAvatar class="border" name="sun" {size} /> <span class="font-mono text-xs text-neutral-600 dark:text-neutral-400">{size}px</span> </div> {/each}</div>Animated
Compare hover-enabled rendering with a static variant when you want motion only in emphasis-heavy surfaces.
Animated
Hover to animate
Static
Animation disabled
animated-example.svelte
<script lang="ts"> import { FallbackAvatar } from "$lib/components/spell/fallback-avatar/index.js";</script>
<div class="flex flex-wrap items-center gap-6"> <div class="flex flex-col items-center gap-2"> <FallbackAvatar class="border" name="animated" size={56} /> <div class="text-center"> <p class="text-sm font-medium">Animated</p> <p class="text-muted-foreground text-xs">Hover to animate</p> </div> </div>
<div class="flex flex-col items-center gap-2"> <FallbackAvatar class="border" name="animated" size={56} animated={false} /> <div class="text-center"> <p class="text-sm font-medium">Static</p> <p class="text-muted-foreground text-xs">Animation disabled</p> </div> </div></div>Props
| Name | Type | Default | Description |
|---|---|---|---|
name | string | required | The seed used to derive the avatar composition, color palette, and motion anchors. |
size | number | 32 | Controls the rendered avatar size in CSS pixels. |
animated | boolean | true | Enables the hover-only animation loop for the avatar surface. |
class | ClassValue | undefined | Custom classes merged onto the root canvas element. |
style | string | undefined | Inline styles appended to the root canvas element. |