Pixel Trail

Pointer trail rendered as a grid of square pixels on a WebGL canvas, with optional gooey filter and an auto-motion mode.

pnpm dlx shadcn@latest add @leo/pixel-trail

Props

NameTypeDefaultDescription
autoMotionboolean | undefinedfalseDrives the trail along a looping path without pointer input (uses the r3f clock).
canvasPropsPartial<CanvasProps> | undefined{}
classNamestring | undefined-
colorstring | undefined#ffffff
easingFunction((x: number) => number) | undefined(x: number) => x
glProps(WebGLContextAttributes & { powerPreference?: string | undefined; }) | undefined{ antialias: false, powerPreference: "high-performance", alpha: true, }
gooeyFilter{ id: string; strength: number; } | undefined-
gridSizenumber | undefined40
interpolatenumber | undefined5
maxAgenumber | undefined250
trailSizenumber | undefined0.1

Dependencies

  • @react-three/drei@^10.7.4
  • @react-three/fiber@^9.3.0
  • three@^0.180.0

Source

"use client";

import { shaderMaterial, useTrailTexture } from "@react-three/drei";
import { Canvas, type CanvasProps, type ThreeEvent, useFrame, useThree } from "@react-three/fiber";
import type React from "react";
import { useEffect, useMemo, useState } from "react";
import * as THREE from "three";
import { cn } from "@/lib/utils";

interface GooeyFilterProps {
  id?: string;
  strength?: number;
}

interface DotMaterialUniforms {
  resolution: THREE.Vector2;
  mouseTrail: THREE.Texture | null;
  gridSize: number;
  pixelColor: THREE.Color;
}

interface SceneProps {
  gridSize: number;
  trailSize: number;
  maxAge: number;
  interpolate: number;
  easingFunction: (x: number) => number;
  pixelColor: string;
  autoMotion: boolean;
}

export interface PixelTrailProps {
  gridSize?: number;
  trailSize?: number;
  maxAge?: number;
  interpolate?: number;
  easingFunction?: (x: number) => number;
  canvasProps?: Partial<CanvasProps>;
  glProps?: WebGLContextAttributes & { powerPreference?: string };
  gooeyFilter?: { id: string; strength: number };
  color?: string;
  /** Drives the trail along a looping path without pointer input (uses the r3f clock). */
  autoMotion?: boolean;
  className?: string;
}

const GooeyFilter: React.FC<GooeyFilterProps> = ({ id = "goo-filter", strength = 10 }) => {
  return (
    <svg className="z-1 absolute overflow-hidden" aria-hidden="true">
      <defs>
        <filter id={id}>
          <feGaussianBlur in="SourceGraphic" stdDeviation={strength} result="blur" />
          <feColorMatrix
            in="blur"
            type="matrix"
            values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 19 -9"
            result="goo"
          />
          <feComposite in="SourceGraphic" in2="goo" operator="atop" />
        </filter>
      </defs>
    </svg>
  );
};

const DotMaterial = shaderMaterial(
  {
    resolution: new THREE.Vector2(),
    mouseTrail: null,
    gridSize: 100,
    pixelColor: new THREE.Color("#ffffff"),
  },
  /* glsl vertex shader */ `
    varying vec2 vUv;
    void main() {
      gl_Position = vec4(position.xy, 0.0, 1.0);
    }
  `,
  /* glsl fragment shader */ `
    uniform vec2 resolution;
    uniform sampler2D mouseTrail;
    uniform float gridSize;
    uniform vec3 pixelColor;

    vec2 coverUv(vec2 uv) {
      vec2 s = resolution.xy / max(resolution.x, resolution.y);
      vec2 newUv = (uv - 0.5) * s + 0.5;
      return clamp(newUv, 0.0, 1.0);
    }

    float sdfCircle(vec2 p, float r) {
        return length(p - 0.5) - r;
    }

    void main() {
      vec2 screenUv = gl_FragCoord.xy / resolution;
      vec2 uv = coverUv(screenUv);

      vec2 gridUv = fract(uv * gridSize);
      vec2 gridUvCenter = (floor(uv * gridSize) + 0.5) / gridSize;

      float trail = texture2D(mouseTrail, gridUvCenter).r;

      gl_FragColor = vec4(pixelColor, trail);
    }
  `,
);

const identityEase = (x: number) => x;
const DEFAULT_CANVAS_PROPS: Partial<CanvasProps> = {};
const DEFAULT_GL_PROPS: PixelTrailProps["glProps"] = {
  antialias: false,
  powerPreference: "high-performance",
  alpha: true,
};

function Scene({
  gridSize,
  trailSize,
  maxAge,
  interpolate,
  easingFunction,
  pixelColor,
  autoMotion,
}: SceneProps) {
  const size = useThree((s) => s.size);
  const viewport = useThree((s) => s.viewport);

  const dotMaterial = useMemo(() => new DotMaterial(), []);
  useEffect(() => {
    return () => {
      dotMaterial.dispose();
    };
  }, [dotMaterial]);

  useEffect(() => {
    (dotMaterial.uniforms.pixelColor.value as THREE.Color).set(pixelColor);
  }, [dotMaterial, pixelColor]);

  // drei's declared return type differs across 10.x releases; pin the shape this component uses.
  const [trail, onMove] = useTrailTexture({
    size: 512,
    radius: trailSize,
    maxAge: maxAge,
    interpolate: interpolate || 0.1,
    ease: easingFunction || identityEase,
  }) as unknown as [THREE.Texture | null, (e: ThreeEvent<PointerEvent>) => void];

  useEffect(() => {
    if (!trail) return;
    trail.minFilter = THREE.NearestFilter;
    trail.magFilter = THREE.NearestFilter;
    trail.wrapS = THREE.ClampToEdgeWrapping;
    trail.wrapT = THREE.ClampToEdgeWrapping;
  }, [trail]);

  const autoUv = useMemo(() => new THREE.Vector2(), []);
  useFrame((state) => {
    if (!autoMotion) return;
    const t = state.clock.elapsedTime;
    // The visible part of the (square) trail texture is the canvas aspect ratio around its centre.
    const longSide = Math.max(size.width, size.height);
    const spanX = (size.width / longSide) * 0.42;
    const spanY = (size.height / longSide) * 0.42;
    autoUv.set(0.5 + spanX * Math.sin(t * 1.7), 0.5 + spanY * Math.sin(t * 2.3 + 1));
    (onMove as unknown as (e: { uv: THREE.Vector2 }) => void)({ uv: autoUv });
  });

  const scale = Math.max(viewport.width, viewport.height) / 2;

  return (
    <mesh scale={[scale, scale, 1]} onPointerMove={onMove}>
      <planeGeometry args={[2, 2]} />
      <primitive
        object={dotMaterial}
        attach="material"
        gridSize={gridSize}
        resolution={[size.width * viewport.dpr, size.height * viewport.dpr]}
        mouseTrail={trail}
      />
    </mesh>
  );
}

// react-use-measure (inside <Canvas>) feeds its ResizeObserver through the scroll debounce, a 50 ms
// timer; with no debounce the canvas gets its size on the first observation.
const CANVAS_RESIZE = { debounce: 0 };

// r3f 9 rethrows a failed renderer creation while rendering <Canvas>, which would unmount the whole app.
// Starts false so the server render and the first client render match.
function useWebGLSupported() {
  const [supported, setSupported] = useState(false);
  useEffect(() => {
    const canvas = document.createElement("canvas");
    const gl = canvas.getContext("webgl2") ?? canvas.getContext("webgl");
    gl?.getExtension("WEBGL_lose_context")?.loseContext();
    setSupported(gl !== null);
  }, []);
  return supported;
}

export function PixelTrail({
  gridSize = 40,
  trailSize = 0.1,
  maxAge = 250,
  interpolate = 5,
  easingFunction = identityEase,
  canvasProps = DEFAULT_CANVAS_PROPS,
  glProps = DEFAULT_GL_PROPS,
  gooeyFilter,
  color = "#ffffff",
  autoMotion = false,
  className,
}: PixelTrailProps) {
  const webgl = useWebGLSupported();
  return (
    <div className={cn("absolute inset-0 z-1", className)} aria-hidden="true">
      {gooeyFilter && <GooeyFilter id={gooeyFilter.id} strength={gooeyFilter.strength} />}
      {webgl && (
        <Canvas
          resize={CANVAS_RESIZE}
          {...canvasProps}
          dpr={canvasProps.dpr ?? [1, 1.25]}
          // The shader writes straight (non-premultiplied) colour, so a fully transparent texel would
          // otherwise composite as solid colour; a user glProps can still override it.
          gl={{ premultipliedAlpha: false, ...glProps }}
          style={gooeyFilter ? { filter: `url(#${gooeyFilter.id})` } : undefined}
        >
          <Scene
            gridSize={gridSize}
            trailSize={trailSize}
            maxAge={maxAge}
            interpolate={interpolate}
            easingFunction={easingFunction}
            pixelColor={color}
            autoMotion={autoMotion}
          />
        </Canvas>
      )}
    </div>
  );
}

export default PixelTrail;