Grid Distortion

An image on a WebGL grid that warps and relaxes as the pointer drags across it; ships a generated default image.

pnpm dlx shadcn@latest add @leo/grid-distortion

Props

NameTypeDefaultDescription
autoMotionboolean | undefinedfalseDrives a virtual pointer along a looping path while the real pointer is not over the container.
classNamestring | undefined
gridnumber | undefined15
imageSrcstring | undefined`data:image/svg+xml;utf8,${encodeURIComponent( `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800" viewBox="0 0 1200 800"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0f172a"/><stop offset="0.5" stop-color="#4338ca"/><stop offset="1" stop-color="#db2777"/></linearGradient></defs><rect width="1200" height="800" fill="url(#g)"/><g stroke="#fff" stroke-opacity="0.35" stroke-width="3">${Array.from({ length: 13 }, (_, i) => `<path d="M${i * 100} 0V800"/>`).join("")}${Array.from({ length: 9 }, (_, i) => `<path d="M0 ${i * 100}H1200"/>`).join("")}</g><g fill="none" stroke="#fde68a" stroke-width="8"><circle cx="600" cy="400" r="150"/><circle cx="600" cy="400" r="260"/></g><circle cx="600" cy="400" r="70" fill="#fde68a"/></svg>`, )}`
mousenumber | undefined0.1
relaxationnumber | undefined0.9
strengthnumber | undefined0.15

Dependencies

  • three@^0.180.0

Source

"use client";

import type React from "react";
import { useEffect, useRef } from "react";
import * as THREE from "three";
import { cn } from "@/lib/utils";

export interface GridDistortionProps {
  grid?: number;
  mouse?: number;
  strength?: number;
  relaxation?: number;
  imageSrc?: string;
  /** Drives a virtual pointer along a looping path while the real pointer is not over the container. */
  autoMotion?: boolean;
  className?: string;
}

// Generated image so the default render needs no network; width/height attributes give the
// texture loader an intrinsic size for SVG.
const DEFAULT_IMAGE_SRC = `data:image/svg+xml;utf8,${encodeURIComponent(
  `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800" viewBox="0 0 1200 800"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0f172a"/><stop offset="0.5" stop-color="#4338ca"/><stop offset="1" stop-color="#db2777"/></linearGradient></defs><rect width="1200" height="800" fill="url(#g)"/><g stroke="#fff" stroke-opacity="0.35" stroke-width="3">${Array.from({ length: 13 }, (_, i) => `<path d="M${i * 100} 0V800"/>`).join("")}${Array.from({ length: 9 }, (_, i) => `<path d="M0 ${i * 100}H1200"/>`).join("")}</g><g fill="none" stroke="#fde68a" stroke-width="8"><circle cx="600" cy="400" r="150"/><circle cx="600" cy="400" r="260"/></g><circle cx="600" cy="400" r="70" fill="#fde68a"/></svg>`,
)}`;

const vertexShader = `
uniform float time;
varying vec2 vUv;
varying vec3 vPosition;

void main() {
  vUv = uv;
  vPosition = position;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;

const fragmentShader = `
uniform sampler2D uDataTexture;
uniform sampler2D uTexture;
uniform vec4 resolution;
varying vec2 vUv;

void main() {
  vec2 uv = vUv;
  vec4 offset = texture2D(uDataTexture, vUv);
  gl_FragColor = texture2D(uTexture, uv - 0.02 * offset.rg);
}
`;

const GridDistortion: React.FC<GridDistortionProps> = ({
  grid = 15,
  mouse = 0.1,
  strength = 0.15,
  relaxation = 0.9,
  imageSrc = DEFAULT_IMAGE_SRC,
  autoMotion = false,
  className = "",
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const sceneRef = useRef<THREE.Scene | null>(null);
  const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
  const cameraRef = useRef<THREE.OrthographicCamera | null>(null);
  const planeRef = useRef<THREE.Mesh | null>(null);
  const imageAspectRef = useRef<number>(1);
  const animationIdRef = useRef<number | null>(null);
  const resizeObserverRef = useRef<ResizeObserver | null>(null);

  useEffect(() => {
    if (!containerRef.current) return;

    const container = containerRef.current;

    const scene = new THREE.Scene();
    sceneRef.current = scene;

    let renderer: THREE.WebGLRenderer;
    try {
      renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,
        powerPreference: "high-performance",
      });
    } catch {
      // No WebGL context available: render an empty container.
      return;
    }
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
    renderer.setClearColor(0x000000, 0);
    rendererRef.current = renderer;

    container.innerHTML = "";
    container.appendChild(renderer.domElement);

    const camera = new THREE.OrthographicCamera(0, 0, 0, 0, -1000, 1000);
    camera.position.z = 2;
    cameraRef.current = camera;

    const uniforms = {
      time: { value: 0 },
      resolution: { value: new THREE.Vector4() },
      uTexture: { value: null as THREE.Texture | null },
      uDataTexture: { value: null as THREE.DataTexture | null },
    };

    let disposed = false;
    const textureLoader = new THREE.TextureLoader();
    textureLoader.load(imageSrc, (texture) => {
      if (disposed) {
        texture.dispose();
        return;
      }
      texture.minFilter = THREE.LinearFilter;
      texture.magFilter = THREE.LinearFilter;
      texture.wrapS = THREE.ClampToEdgeWrapping;
      texture.wrapT = THREE.ClampToEdgeWrapping;
      imageAspectRef.current = texture.image.width / texture.image.height;
      uniforms.uTexture.value = texture;
      handleResize();
    });

    const size = grid;
    const data = new Float32Array(4 * size * size);
    for (let i = 0; i < size * size; i++) {
      data[i * 4] = Math.random() * 255 - 125;
      data[i * 4 + 1] = Math.random() * 255 - 125;
    }

    const dataTexture = new THREE.DataTexture(data, size, size, THREE.RGBAFormat, THREE.FloatType);
    dataTexture.needsUpdate = true;
    uniforms.uDataTexture.value = dataTexture;

    const material = new THREE.ShaderMaterial({
      side: THREE.DoubleSide,
      uniforms,
      vertexShader,
      fragmentShader,
      transparent: true,
    });

    const geometry = new THREE.PlaneGeometry(1, 1, size - 1, size - 1);
    const plane = new THREE.Mesh(geometry, material);
    planeRef.current = plane;
    scene.add(plane);

    const handleResize = () => {
      if (!container || !renderer || !camera) return;

      const rect = container.getBoundingClientRect();
      const width = rect.width;
      const height = rect.height;

      if (width === 0 || height === 0) return;

      const containerAspect = width / height;

      renderer.setSize(width, height);

      if (plane) {
        plane.scale.set(containerAspect, 1, 1);
      }

      const frustumHeight = 1;
      const frustumWidth = frustumHeight * containerAspect;
      camera.left = -frustumWidth / 2;
      camera.right = frustumWidth / 2;
      camera.top = frustumHeight / 2;
      camera.bottom = -frustumHeight / 2;
      camera.updateProjectionMatrix();

      uniforms.resolution.value.set(width, height, 1, 1);
    };

    if (window.ResizeObserver) {
      const resizeObserver = new ResizeObserver(() => {
        handleResize();
      });
      resizeObserver.observe(container);
      resizeObserverRef.current = resizeObserver;
    } else {
      window.addEventListener("resize", handleResize);
    }

    const mouseState = {
      x: 0,
      y: 0,
      prevX: 0,
      prevY: 0,
      vX: 0,
      vY: 0,
    };

    const autoPointer = (now: number) => {
      const t = now * 0.001;
      return { x: 0.5 + 0.35 * Math.sin(t * 2.1), y: 0.5 + 0.3 * Math.sin(t * 1.7 + 1) };
    };

    let hovering = false;
    const handleMouseMove = (e: MouseEvent) => {
      hovering = true;
      const rect = container.getBoundingClientRect();
      const x = (e.clientX - rect.left) / rect.width;
      const y = 1 - (e.clientY - rect.top) / rect.height;
      mouseState.vX = x - mouseState.prevX;
      mouseState.vY = y - mouseState.prevY;
      Object.assign(mouseState, { x, y, prevX: x, prevY: y });
    };

    const handleMouseLeave = () => {
      hovering = false;
      if (dataTexture) {
        dataTexture.needsUpdate = true;
      }
      // Rest where the virtual pointer is now: with autoMotion, resetting prev to 0 would turn the next
      // frame's delta into a huge velocity impulse.
      const { x, y } = autoMotion ? autoPointer(performance.now()) : { x: 0, y: 0 };
      Object.assign(mouseState, { x, y, prevX: x, prevY: y, vX: 0, vY: 0 });
    };

    container.addEventListener("mousemove", handleMouseMove);
    container.addEventListener("mouseleave", handleMouseLeave);

    handleResize();

    const animate = (now: number) => {
      animationIdRef.current = requestAnimationFrame(animate);

      if (!renderer || !scene || !camera) return;

      uniforms.time.value += 0.05;

      if (autoMotion && !hovering) {
        const { x, y } = autoPointer(now);
        mouseState.vX = x - mouseState.prevX;
        mouseState.vY = y - mouseState.prevY;
        Object.assign(mouseState, { x, y, prevX: x, prevY: y });
      }

      if (!(dataTexture.image.data instanceof Float32Array)) {
        console.error("dataTexture.image.data is not a Float32Array");
        return;
      }
      const data: Float32Array = dataTexture.image.data;
      for (let i = 0; i < size * size; i++) {
        data[i * 4] *= relaxation;
        data[i * 4 + 1] *= relaxation;
      }

      const gridMouseX = size * mouseState.x;
      const gridMouseY = size * mouseState.y;
      const maxDist = size * mouse;

      for (let i = 0; i < size; i++) {
        for (let j = 0; j < size; j++) {
          const distSq = (gridMouseX - i) ** 2 + (gridMouseY - j) ** 2;
          if (distSq < maxDist * maxDist) {
            const index = 4 * (i + size * j);
            const power = Math.min(maxDist / Math.sqrt(distSq), 10);
            data[index] += strength * 100 * mouseState.vX * power;
            data[index + 1] -= strength * 100 * mouseState.vY * power;
          }
        }
      }

      dataTexture.needsUpdate = true;
      renderer.render(scene, camera);
    };

    animationIdRef.current = requestAnimationFrame(animate);

    return () => {
      disposed = true;
      if (animationIdRef.current) {
        cancelAnimationFrame(animationIdRef.current);
      }

      if (resizeObserverRef.current) {
        resizeObserverRef.current.disconnect();
      } else {
        window.removeEventListener("resize", handleResize);
      }

      container.removeEventListener("mousemove", handleMouseMove);
      container.removeEventListener("mouseleave", handleMouseLeave);

      if (renderer) {
        renderer.dispose();
        renderer.forceContextLoss();
        if (container.contains(renderer.domElement)) {
          container.removeChild(renderer.domElement);
        }
      }

      if (geometry) geometry.dispose();
      if (material) material.dispose();
      if (dataTexture) dataTexture.dispose();
      if (uniforms.uTexture.value) uniforms.uTexture.value.dispose();

      sceneRef.current = null;
      rendererRef.current = null;
      cameraRef.current = null;
      planeRef.current = null;
    };
  }, [grid, mouse, strength, relaxation, imageSrc, autoMotion]);

  return (
    <div
      ref={containerRef}
      aria-hidden="true"
      className={cn("relative overflow-hidden", className)}
      style={{
        width: "100%",
        height: "100%",
        minWidth: "0",
        minHeight: "0",
      }}
    />
  );
};

export { GridDistortion };
export default GridDistortion;