VibeCoderzVibeCoderz
Telegram
All Prompts
backgroundanimation

Prism Background

WebGL-эффект фона с призмами/пирамидами для сайтов. Поддержка анимации (вращение, наведение) и кастомизации. Идеально для React.

by Zhou JasonLive Preview

Prompt

# Prism Background

You are given a task to integrate an existing React component in the codebase

~~~/README.md
# PrismBackground

A premium, high-performance WebGL background effect that renders an interactive, procedurally generated prism/pyramid structure. Built with **OGL** for maximum performance and low memory overhead.

## Features

- **High Performance**: Direct WebGL rendering with OGL (tiny footprint).
- **Multiple Animation Modes**:
  - `rotate`: Smooth base wobble effect.
  - `hover`: Real-time cursor tracking with inertia.
  - `3drotate`: Full 3D spatial rotation.
- **Deep Customization**: Adjust geometry (height, base width), visual effects (glow, noise, bloom), and colors (hue shift, frequency).
- **Optimized**: Supports intersection observer to pause rendering when offscreen.

## Dependencies

- `ogl`: ^0.0.116
- `react`: ^18.2.0
- `lucide-react`: ^0.344.0

## API Reference

### Props

| Prop | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `height` | `number` | `3.5` | Height of the prism geometry. |
| `baseWidth` | `number` | `5.5` | Width of the prism base. |
| `animationType` | `'rotate' \| 'hover' \| '3drotate'` | `'rotate'` | The animation behavior. |
| `glow` | `number` | `1` | Intensity of the glow effect. |
| `offset` | `{ x?: number; y?: number }` | `{ x: 0, y: 0 }` | Center offset in pixels. |
| `noise` | `number` | `0.5` | Grainy noise intensity (0 to 1). |
| `transparent` | `boolean` | `true` | Whether the canvas background is transparent. |
| `scale` | `number` | `3.6` | Overall scale of the rendered output. |
| `hueShift` | `number` | `0` | Color hue shift in radians. |
| `colorFrequency` | `number` | `1` | Density of the color waves. |
| `hoverStrength` | `number` | `2` | Multiplier for hover displacement (hover mode only). |
| `inertia` | `number` | `0.05` | Smoothness of movement (0 to 1). |
| `bloom` | `number` | `1` | Bloom/brightness multiplier. |
| `suspendWhenOffscreen` | `boolean` | `false` | Pause rendering when not in viewport. |
| `timeScale` | `number` | `0.5` | Global animation speed multiplier. |
| `className` | `string` | `""` | Additional CSS classes for the container. |

## Usage Example

```tsx
import { PrismBackground } from '@/sd-components/063b23ed-a3ad-48cd-96fc-40b93e3a44a3';

function MyPage() {
  return (
    <div className="relative w-full h-screen bg-black">
      <PrismBackground
        animationType="hover"
        glow={1.2}
        hueShift={0.5}
        scale={4}
        suspendWhenOffscreen={true}
      />
      <div className="relative z-10 text-white">
        Your content here
      </div>
    </div>
  );
}
```
~~~

~~~/src/App.tsx
import React, { useState } from 'react';
import PrismBackground from './Component';
import { RotateCcw, MousePointer2, Box, RefreshCw } from 'lucide-react';

export default function App() {
  const [animationType, setAnimationType] = useState<'rotate' | 'hover' | '3drotate'>('rotate');

  const cycleAnimation = () => {
    const modes: ('rotate' | 'hover' | '3drotate')[] = ['rotate', 'hover', '3drotate'];
    const nextIndex = (modes.indexOf(animationType) + 1) % modes.length;
    setAnimationType(modes[nextIndex]);
  };

  return (
    <div className="w-full h-screen bg-[#1A1A1B] flex flex-col items-center justify-center p-20 overflow-hidden relative font-sans">
      {/* Background Layer */}
      <div className="absolute inset-0 z-0">
        <PrismBackground
          animationType={animationType}
          timeScale={0.5}
          height={3.5}
          baseWidth={5.5}
          scale={3.6}
          hueShift={0}
          colorFrequency={1}
          noise={0.5}
          glow={1}
          suspendWhenOffscreen={true}
        />
      </div>

      {/* Foreground Showcase Content */}
      <div className="relative z-10 flex flex-col items-center justify-center pointer-events-none">
        <div className="bg-[#F9F9F9]/5 backdrop-blur-xl border border-white/10 p-12 rounded-[2.5rem] shadow-[0_40px_100px_rgba(0,0,0,0.4)] flex flex-col items-center max-w-lg text-center space-y-6">
          <h1 className="text-white text-5xl font-medium tracking-tight">
            Prism Background
          </h1>
          <p className="text-white/60 text-lg font-normal leading-relaxed">
             A high-performance WebGL shader effect for premium interfaces.
          </p>
          
          <div className="flex items-center space-x-4 pt-4 pointer-events-auto">
             <button 
                onClick={cycleAnimation}
                className="flex items-center space-x-3 px-6 py-3 bg-white text-black rounded-full hover:scale-105 active:scale-95 transition-all duration-300 shadow-xl group"
             >
                <RefreshCw className="w-5 h-5 group-hover:rotate-180 transition-transform duration-500" />
                <span className="font-semibold capitalize">{animationType} Mode</span>
             </button>
             
             <button 
                onClick={() => window.location.reload()}
                className="p-3 bg-white/10 hover:bg-white/20 text-white rounded-full transition-colors backdrop-blur-md border border-white/5"
                title="Reset Animation"
             >
                <RotateCcw className="w-5 h-5" />
             </button>
          </div>
        </div>
      </div>

      {/* Feature Labels */}
      <div className="absolute bottom-12 left-1/2 -translate-x-1/2 flex items-center space-x-12 z-10 pointer-events-none">
          <div className="flex flex-col items-center space-y-1">
            <Box className="text-white/30 w-5 h-5 mb-1" />
            <span className="text-white/40 text-[10px] uppercase tracking-[0.2em] font-medium">WebGL OGL</span>
          </div>
          <div className="flex flex-col items-center space-y-1">
            <MousePointer2 className="text-white/30 w-5 h-5 mb-1" />
            <span className="text-white/40 text-[10px] uppercase tracking-[0.2em] font-medium">Interactive</span>
          </div>
          <div className="flex flex-col items-center space-y-1">
            <RotateCcw className="text-white/30 w-5 h-5 mb-1" />
            <span className="text-white/40 text-[10px] uppercase tracking-[0.2em] font-medium">Procedural</span>
          </div>
      </div>
    </div>
  );
}
~~~

~~~/package.json
{
  "name": "prism-background",
  "description": "A premium, high-performance WebGL prism background effect using OGL.",
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "ogl": "^0.0.116",
    "lucide-react": "^0.344.0"
  }
}
~~~

~~~/src/Component.tsx
/**
 * PrismBackground Component
 * A high-performance WebGL background effect that renders an interactive prism/pyramid.
 * Uses OGL for low-level GL control and high efficiency.
 * 
 * Features:
 * - 3 Animation modes: rotate, hover, 3drotate
 * - Customizable geometry: height, baseWidth, scale
 * - Visual effects: glow, noise, bloom, hueShift, colorFrequency
 * - Performance: Suspend when offscreen, requestAnimationFrame optimization
 */

import React, { useEffect, useRef } from 'react';
import { Renderer, Triangle, Program, Mesh } from 'ogl';

export type PrismProps = {
  /** Height of the prism geometry */
  height?: number;
  /** Width of the prism base */
  baseWidth?: number;
  /** Animation style: 'rotate' (base wobble), 'hover' (cursor tracking), '3drotate' (full space rotation) */
  animationType?: 'rotate' | 'hover' | '3drotate';
  /** Intensity of the glow effect */
  glow?: number;
  /** Center offset in pixels */
  offset?: { x?: number; y?: number };
  /** Grainy noise intensity (0 to 1) */
  noise?: number;
  /** Whether the background is transparent */
  transparent?: boolean;
  /** Overall scale of the rendered output */
  scale?: number;
  /** Color hue shift in radians */
  hueShift?: number;
  /** Density of the color waves */
  colorFrequency?: number;
  /** Multiplier for hover displacement (hover mode only) */
  hoverStrength?: number;
  /** Smoothness of movement (0 to 1) */
  inertia?: number;
  /** Bloom/brightness multiplier */
  bloom?: number;
  /** Pause rendering when component is not in viewport */
  suspendWhenOffscreen?: boolean;
  /** Global animation speed multiplier */
  timeScale?: number;
  /** Container class name */
  className?: string;
};

export const PrismBackground: React.FC<PrismProps> = ({
  height = 3.5,
  baseWidth = 5.5,
  animationType = 'rotate',
  glow = 1,
  offset = { x: 0, y: 0 },
  noise = 0.5,
  transparent = true,
  scale = 3.6,
  hueShift = 0,
  colorFrequency = 1,
  hoverStrength = 2,
  inertia = 0.05,
  bloom = 1,
  suspendWhenOffscreen = false,
  timeScale = 0.5,
  className = ""
}) => {
  const containerRef = useRef<HTMLDivElement | null>(null);

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

    const H = Math.max(0.001, height);
    const BW = Math.max(0.001, baseWidth);
    const BASE_HALF = BW * 0.5;
    const GLOW = Math.max(0.0, glow);
    const NOISE = Math.max(0.0, noise);
    const offX = offset?.x ?? 0;
    const offY = offset?.y ?? 0;
    const SAT = transparent ? 1.5 : 1;
    const SCALE = Math.max(0.001, scale);
    const HUE = hueShift || 0;
    const CFREQ = Math.max(0.0, colorFrequency || 1);
    const BLOOM = Math.max(0.0, bloom || 1);
    const RSX = 1;
    const RSY = 1;
    const RSZ = 1;
    const TS = Math.max(0, timeScale || 1);
    const HOVSTR = Math.max(0, hoverStrength || 1);
    const INERT = Math.max(0, Math.min(1, inertia || 0.12));

    const dpr = Math.min(2, window.devicePixelRatio || 1);
    const renderer = new Renderer({
      dpr,
      alpha: transparent,
      antialias: false
    });

    const gl = renderer.gl;
    gl.disable(gl.DEPTH_TEST);
    gl.disable(gl.CULL_FACE);
    gl.disable(gl.BLEND);

    Object.assign(gl.canvas.style, {
      position: 'absolute',
      inset: '0',
      width: '100%',
      height: '100%',
      display: 'block'
    } as Partial<CSSStyleDeclaration>);

    container.appendChild(gl.canvas);

    const vertex = /* glsl */ `
      attribute vec2 position;
      void main() {
        gl_Position = vec4(position, 0.0, 1.0);
      }
    `;

    const fragment = /* glsl */ `
      precision highp float;
      uniform vec2  iResolution;
      uniform float iTime;
      uniform float uHeight;
      uniform float uBaseHalf;
      uniform mat3  uRot;
      uniform int   uUseBaseWobble;
      uniform float uGlow;
      uniform vec2  uOffsetPx;
      uniform float uNoise;
      uniform float uSaturation;
      uniform float uScale;
      uniform float uHueShift;
      uniform float uColorFreq;
      uniform float uBloom;
      uniform float uCenterShift;
      uniform float uInvBaseHalf;
      uniform float uInvHeight;
      uniform float uMinAxis;
      uniform float uPxScale;
      uniform float uTimeScale;

      vec4 tanh4(vec4 x){
        vec4 e2x = exp(2.0*x);
        return (e2x - 1.0) / (e2x + 1.0);
      }

      float rand(vec2 co){
        return fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453123);
      }

      float sdOctaAnisoInv(vec3 p){
        vec3 q = vec3(abs(p.x) * uInvBaseHalf, abs(p.y) * uInvHeight, abs(p.z) * uInvBaseHalf);
        float m = q.x + q.y + q.z - 1.0;
        return m * uMinAxis * 0.5773502691896258;
      }

      float sdPyramidUpInv(vec3 p){
        float oct = sdOctaAnisoInv(p);
        float halfSpace = -p.y;
        return max(oct, halfSpace);
      }

      mat3 hueRotation(float a){
        float c = cos(a), s = sin(a);
        mat3 W = mat3(
          0.299, 0.587, 0.114,
          0.299, 0.587, 0.114,
          0.299, 0.587, 0.114
        );
        mat3 U = mat3(
           0.701, -0.587, -0.114,
          -0.299,  0.413, -0.114,
          -0.300, -0.588,  0.886
        );
        mat3 V = mat3(
           0.168, -0.331,  0.500,
           0.328,  0.035, -0.500,
          -0.497,  0.296,  0.201
        );
        return W + U * c + V * s;
      }

      void main(){
        vec2 f = (gl_FragCoord.xy - 0.5 * iResolution.xy - uOffsetPx) * uPxScale;
        float z = 5.0;
        float d = 0.0;
        vec3 p;
        vec4 o = vec4(0.0);
        float centerShift = uCenterShift;
        float cf = uColorFreq;

        mat2 wob = mat2(1.0);
        if (uUseBaseWobble == 1) {
          float t = iTime * uTimeScale;
          float c0 = cos(t + 0.0);
          float c1 = cos(t + 33.0);
          float c2 = cos(t + 11.0);
          wob = mat2(c0, c1, c2, c0);
        }

        const int STEPS = 100;
        for (int i = 0; i < STEPS; i++) {
          p = vec3(f, z);
          p.xz = p.xz * wob;
          p = uRot * p;
          vec3 q = p;
          q.y += centerShift;
          d = 0.1 + 0.2 * abs(sdPyramidUpInv(q));
          z -= d;
          o += (sin((p.y + z) * cf + vec4(0.0, 1.0, 2.0, 3.0)) + 1.0) / d;
        }

        o = tanh4(o * o * (uGlow * uBloom) / 1e5);
        vec3 col = o.rgb;
        float n = rand(gl_FragCoord.xy + vec2(iTime));
        col += (n - 0.5) * uNoise;
        col = clamp(col, 0.0, 1.0);
        float L = dot(col, vec3(0.2126, 0.7152, 0.0722));
        col = clamp(mix(vec3(L), col, uSaturation), 0.0, 1.0);

        if(abs(uHueShift) > 0.0001){
          col = clamp(hueRotation(uHueShift) * col, 0.0, 1.0);
        }

        gl_FragColor = vec4(col, o.a);
      }
    `;

    const geometry = new Triangle(gl);
    const iResBuf = new Float32Array(2);
    const offsetPxBuf = new Float32Array(2);

    const program = new Program(gl, {
      vertex,
      fragment,
      uniforms: {
        iResolution: { value: iResBuf },
        iTime: { value: 0 },
        uHeight: { value: H },
        uBaseHalf: { value: BASE_HALF },
        uUseBaseWobble: { value: 1 },
        uRot: { value: new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]) },
        uGlow: { value: GLOW },
        uOffsetPx: { value: offsetPxBuf },
        uNoise: { value: NOISE },
        uSaturation: { value: SAT },
        uScale: { value: SCALE },
        uHueShift: { value: HUE },
        uColorFreq: { value: CFREQ },
        uBloom: { value: BLOOM },
        uCenterShift: { value: H * 0.25 },
        uInvBaseHalf: { value: 1 / BASE_HALF },
        uInvHeight: { value: 1 / H },
        uMinAxis: { value: Math.min(BASE_HALF, H) },
        uPxScale: {
          value: 1 / ((gl.drawingBufferHeight || 1) * 0.1 * SCALE)
        },
        uTimeScale: { value: TS }
      }
    });

    const mesh = new Mesh(gl, { geometry, program });

    const resize = () => {
      const w = container.clientWidth || 1;
      const h = container.clientHeight || 1;
      renderer.setSize(w, h);
      iResBuf[0] = gl.drawingBufferWidth;
      iResBuf[1] = gl.drawingBufferHeight;
      offsetPxBuf[0] = offX * dpr;
      offsetPxBuf[1] = offY * dpr;
      program.uniforms.uPxScale.value = 1 / ((gl.drawingBufferHeight || 1) * 0.1 * SCALE);
    };

    const ro = new ResizeObserver(resize);
    ro.observe(container);
    resize();

    const rotBuf = new Float32Array(9);
    const setMat3FromEuler = (yawY: number, pitchX: number, rollZ: number, out: Float32Array) => {
      const cy = Math.cos(yawY), sy = Math.sin(yawY);
      const cx = Math.cos(pitchX), sx = Math.sin(pitchX);
      const cz = Math.cos(rollZ), sz = Math.sin(rollZ);

      const r00 = cy * cz + sy * sx * sz;
      const r01 = -cy * sz + sy * sx * cz;
      const r02 = sy * cx;
      const r10 = cx * sz;
      const r11 = cx * cz;
      const r12 = -sx;
      const r20 = -sy * cz + cy * sx * sz;
      const r21 = sy * sz + cy * sx * cz;
      const r22 = cy * cx;

      out[0] = r00; out[1] = r10; out[2] = r20;
      out[3] = r01; out[4] = r11; out[5] = r21;
      out[6] = r02; out[7] = r12; out[8] = r22;
      return out;
    };

    const NOISE_IS_ZERO = NOISE < 1e-6;
    let raf = 0;
    const t0 = performance.now();

    const startRAF = () => {
      if (raf) return;
      raf = requestAnimationFrame(render);
    };

    const stopRAF = () => {
      if (!raf) return;
      cancelAnimationFrame(raf);
      raf = 0;
    };

    const rnd = () => Math.random();
    const wX = (0.3 + rnd() * 0.6) * RSX;
    const wY = (0.2 + rnd() * 0.7) * RSY;
    const wZ = (0.1 + rnd() * 0.5) * RSZ;
    const phX = rnd() * Math.PI * 2;
    const phZ = rnd() * Math.PI * 2;

    let yaw = 0, pitch = 0, roll = 0;
    let targetYaw = 0, targetPitch = 0;

    const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
    const pointer = { x: 0, y: 0, inside: true };

    const onMove = (e: PointerEvent) => {
      const ww = Math.max(1, window.innerWidth);
      const wh = Math.max(1, window.innerHeight);
      const cx = ww * 0.5;
      const cy = wh * 0.5;
      const nx = (e.clientX - cx) / (ww * 0.5);
      const ny = (e.clientY - cy) / (wh * 0.5);
      pointer.x = Math.max(-1, Math.min(1, nx));
      pointer.y = Math.max(-1, Math.min(1, ny));
      pointer.inside = true;
    };

    const onLeave = () => { pointer.inside = false; };
    const onBlur = () => { pointer.inside = false; };

    let onPointerMove: ((e: PointerEvent) => void) | null = null;
    if (animationType === 'hover') {
      onPointerMove = (e: PointerEvent) => {
        onMove(e);
        startRAF();
      };
      window.addEventListener('pointermove', onPointerMove, { passive: true });
      window.addEventListener('mouseleave', onLeave);
      window.addEventListener('blur', onBlur);
      program.uniforms.uUseBaseWobble.value = 0;
    } else if (animationType === '3drotate') {
      program.uniforms.uUseBaseWobble.value = 0;
    } else {
      program.uniforms.uUseBaseWobble.value = 1;
    }

    const render = (t: number) => {
      const time = (t - t0) * 0.001;
      program.uniforms.iTime.value = time;
      let continueRAF = true;

      if (animationType === 'hover') {
        const maxPitch = 0.6 * HOVSTR;
        const maxYaw = 0.6 * HOVSTR;
        targetYaw = (pointer.inside ? -pointer.x : 0) * maxYaw;
        targetPitch = (pointer.inside ? pointer.y : 0) * maxPitch;

        const prevYaw = yaw;
        const prevPitch = pitch;
        const prevRoll = roll;

        yaw = lerp(prevYaw, targetYaw, INERT);
        pitch = lerp(prevPitch, targetPitch, INERT);
        roll = lerp(prevRoll, 0, 0.1);

        program.uniforms.uRot.value = setMat3FromEuler(yaw, pitch, roll, rotBuf);

        if (NOISE_IS_ZERO) {
          const settled = Math.abs(yaw - targetYaw) < 1e-4 && Math.abs(pitch - targetPitch) < 1e-4 && Math.abs(roll) < 1e-4;
          if (settled) continueRAF = false;
        }
      } else if (animationType === '3drotate') {
        const tScaled = time * TS;
        yaw = tScaled * wY;
        pitch = Math.sin(tScaled * wX + phX) * 0.6;
        roll = Math.sin(tScaled * wZ + phZ) * 0.5;
        program.uniforms.uRot.value = setMat3FromEuler(yaw, pitch, roll, rotBuf);
        if (TS < 1e-6) continueRAF = false;
      } else {
        rotBuf[0] = 1; rotBuf[1] = 0; rotBuf[2] = 0;
        rotBuf[3] = 0; rotBuf[4] = 1; rotBuf[5] = 0;
        rotBuf[6] = 0; rotBuf[7] = 0; rotBuf[8] = 1;
        program.uniforms.uRot.value = rotBuf;
        if (TS < 1e-6) continueRAF = false;
      }

      renderer.render({ scene: mesh });
      if (continueRAF) {
        raf = requestAnimationFrame(render);
      } else {
        raf = 0;
      }
    };

    interface PrismContainer extends HTMLElement {
      __prismIO?: IntersectionObserver;
    }

    if (suspendWhenOffscreen) {
      const io = new IntersectionObserver(entries => {
        const vis = entries.some(e => e.isIntersecting);
        if (vis) startRAF();
        else stopRAF();
      });
      io.observe(container);
      startRAF();
      (container as PrismContainer).__prismIO = io;
    } else {
      startRAF();
    }

    return () => {
      stopRAF();
      ro.disconnect();
      if (animationType === 'hover') {
        if (onPointerMove) window.removeEventListener('pointermove', onPointerMove as EventListener);
        window.removeEventListener('mouseleave', onLeave);
        window.removeEventListener('blur', onBlur);
      }
      if (suspendWhenOffscreen) {
        const io = (container as PrismContainer).__prismIO as IntersectionObserver | undefined;
        if (io) io.disconnect();
        delete (container as PrismContainer).__prismIO;
      }
      if (gl.canvas.parentElement === container) container.removeChild(gl.canvas);
    };
  }, [
    height, baseWidth, animationType, glow, noise, offset?.x, offset?.y, 
    scale, transparent, hueShift, colorFrequency, timeScale, 
    hoverStrength, inertia, bloom, suspendWhenOffscreen
  ]);

  return <div className={`w-full h-full relative overflow-hidden ${className}`} ref={containerRef} />;
};

export default PrismBackground;
~~~

Implementation Guidelines

1. Analyze the component structure, styling, animation implementations
2. Review the component's arguments and state
3. Think through what is the best place to adopt this component/style into the design we are doing
4. Then adopt the component/design to our current system

Help me integrate this into my design
All Prompts