Shader Gradient Documentation

repository·main·Indexed 23 days ago

https://github.com/ruucm/shadergradient

A collection of tools and plugins for Figma, Framer, and React designed to create high-quality shader gradients. Includes the @shadergradient/react core renderer for React applications, @shadergradient/ui for stateless control components, and specialized components like ShaderGradientCanvas, GizmoHelper, and OrthographicCamera.

Tokens
10.9K
Snippets
11
Records
57
Agent score
82%

What's inside Shader Gradient

  1. How @shadergradient/react and @shadergradient/ui differ

    main

    The v2 architecture separates the rendering logic from the user interface:

    • @shadergradient/react: The core renderer. It contains only the ShaderGradient and ShaderGradientCanvas components. It does not include a built-in store or UI controls. You must manage your own state or use the @shadergradient/ui package for controls.
    • @shadergradient/ui: Contains stateless UI and control components. This package is used by the Figma and Framer plugins and is consumed as an ESM bundle (not published to npm).
    • shadergradient-old: The legacy v1 package which includes both the store and the UI. Use this only if you require the old 'with-store' build.
  2. Add React-specific lint rules using eslint-plugin-react-x and eslint-plugin-react-dom

    main

    To enforce React-specific best practices, you can install and integrate eslint-plugin-react-x and eslint-plugin-react-dom. Add their recommended configurations to your tseslint.config array and ensure parserOptions.project is correctly set to your TypeScript configuration files.

    // eslint.config.js
    import reactX from 'eslint-plugin-react-x'
    import reactDom from 'eslint-plugin-react-dom'
    
    export default tseslint.config([
      globalIgnores(['dist']),
      {
        files: ['**/*.{ts,tsx}'],
        extends: [
          // Other configs...
          // Enable lint rules for React
          reactX.configs['recommended-typescript'],
          // Enable lint rules for React DOM
          reactDom.configs.recommended,
        ],
        languageOptions: {
          parserOptions: {
            project: ['./tsconfig.node.json', './tsconfig.app.json'],
            tsconfigRootDir: import.meta.dirname,
          },
          // other options...
        },
      },
    ])
  3. Install @shadergradient/react for React projects

    main

    To use the core renderer in a React application, install @shadergradient/react along with its required peer dependencies: @react-three/fiber, three, three-stdlib, and camera-controls. You should also install @types/three as a dev dependency.

    Installation Commands

    Using npm:

    npm i @shadergradient/react @react-three/fiber three three-stdlib camera-controls
    npm i -D @types/three

    Using yarn:

    yarn add @shadergradient/react @react-three/fiber three three-stdlib camera-controls
    yarn add -D @types/three

    Using pnpm:

    pnpm add @shadergradient/react @react-three/fiber three three-stdlib camera-controls
    pnpm add -D @types/three
    npm i @shadergradient/react @react-three/fiber three three-stdlib camera-controls
    npm i -D @types/three
  4. Use ShaderGradient in a React application

    main

    To render a gradient, wrap the ShaderGradient component inside a ShaderGradientCanvas. You can control the gradient via props or by loading settings from a URL query string.

    Basic Usage

    import { ShaderGradientCanvas, ShaderGradient } from '@shadergradient/react'
    
    function App() {
      return (
        <ShaderGradientCanvas
          style={{ position: 'absolute', inset: 0 }}
          pixelDensity={1.5}
          fov={45}
        >
          <ShaderGradient cDistance={32} cPolarAngle={125} />
        </ShaderGradientCanvas>
      )
    }

    Loading settings from a URL

    Set the control prop to 'query' and provide a urlString to automatically apply settings from a URL (e.g., from shadergradient.co/customize).

    <ShaderGradientCanvas>
      <ShaderGradient
        control='query'
        urlString='https://www.shadergradient.co/customize?animate=on&cDistance=3.6&cPolarAngle=90&color1=%2352ff89&color2=%23dbba95&color3=%23d0bce1&lightType=3d&shader=defaults&type=plane&uFrequency=5.5&uSpeed=0.4&uStrength=4'
      />
    </ShaderGradientCanvas>
    import { ShaderGradientCanvas, ShaderGradient } from '@shadergradient/react'
    
    function App() {
      return (
        <ShaderGradientCanvas
          style={{ position: 'absolute', inset: 0 }}
          pixelDensity={1.5}
          fov={45}
        >
          <ShaderGradient cDistance={32} cPolarAngle={125} />
        </ShaderGradientCanvas>
      )
    }
  5. Enable type-aware ESLint rules for production applications

    main

    When developing a production application using the Vite + React + TypeScript template, it is recommended to enable type-aware lint rules. This involves replacing tseslint.configs.recommended with one of the following type-checked configurations in your eslint.config.js:

    • ...tseslint.configs.recommendedTypeChecked (Recommended)
    • ...tseslint.configs.strictTypeChecked (Stricter rules)
    • ...tseslint.configs.stylisticTypeChecked (Stylistic rules)

    You must also configure languageOptions.parserOptions to point to your tsconfig files.

    export default tseslint.config([
      globalIgnores(['dist']),
      {
        files: ['**/*.{ts,tsx}'],
        extends: [
          // Other configs...
    
          // Remove tseseslint.configs.recommended and replace with this
          ...tseslint.configs.recommendedTypeChecked,
          // Alternatively, use this for stricter rules
          ...tseslint.configs.strictTypeChecked,
          // Optionally, add this for stylistic rules
          ...tseslint.configs.stylisticTypeChecked,
    
          // Other configs...
        ],
        languageOptions: {
          parserOptions: {
            project: ['./tsconfig.node.json', './tsconfig.app.json'],
            tsconfigRootDir: import.meta.dirname,
          },
          // other options...
        },
      },
    ])
  6. Configure Lighting and Environment Presets

    main

    Lighting is controlled via LightTypeT and EnvironmentPresetT. These can be applied directly to a GradientT object.

    Light Types

    • 3d: Standard 3D lighting.
    • env: Environment-based lighting.

    Environment Presets

    • city
    • dawn
    • lobby

    Lighting Configuration Object

    If using the LightsT structure:

    • lightType: The type of light.
    • brightness: Numerical brightness value.
    • envPreset: The selected environment preset.
  7. Configure the Framer plugin build with tsup

    main

    The Framer plugin uses tsup for bundling. The configuration is specifically tuned to handle compatibility issues between @react-three/fiber dependencies (like react-reconciler and scheduler) and Framer's production React environment.

    Key configuration behaviors:

    • Platform & Format: Targets browser and outputs esm.
    • Minification: minify is set to false because minifying the build causes errors in react-reconciler within Framer.
    • External Dependencies: react and framer are marked as external because Framer's canvas sandbox provides them via import maps. All other dependencies, including three, @react-three/fiber, and react-reconciler, must be bundled using noExternal to avoid resolution errors in the sandbox.
    • Environment: process.env.NODE_ENV is forced to 'production'.
    • Plugins: Uses a custom glslLoader for shader files and a reconcilerProdPlugin to wrap CommonJS versions of react-reconciler and scheduler into eager ESM modules to prevent runtime crashes.
    export default defineConfig(async (options) => {
      // ... configuration logic
      return {
        entry: await globby([`${basePath}/**/*.(t|j)s*`, `!${basePath}/**/*.d.ts`]),
        platform: 'browser',
        format: ['esm'],
        dts: {
          entry: 'src/index.ts',
        },
        minify: false,
        clean: true,
        define: {
          'process.env.NODE_ENV': JSON.stringify('production'),
        },
        external: ['react', 'framer'],
        noExternal: ['three', '@react-three/fiber', 'react-reconciler'],
        esbuildPlugins: [glslLoader, reconcilerProdPlugin, commonjsPlugin()],
        // ...
      }
    })
  8. Configure the Framer build via tsup

    main

    The @shadergradient/ui package uses a specialized tsup configuration for Framer compatibility. Key constraints for this build include:

    • Minification: minify must be set to false. Enabling minification causes react-reconciler errors in Framer.
    • Platform: The target platform is browser.
    • Format: The build outputs in esm format.
    • External Dependencies: To avoid resolution errors (e.g., "Dynamic require of 'react' is not supported"), react, framer, and react-reconciler must be marked as external.
    • GLSL Support: The build includes a custom glsl-loader plugin to handle .glsl, .vs, .fs, .vert, and .frag files by importing them as default string exports.
    export default defineConfig(async (options) => {
      // ...
      return {
        entry: await globby([`${basePath}/**/*.(t|j)s*`, `!${basePath}/**/*.d.ts`]),
        platform: 'browser',
        format: ['esm'],
        dts: {
          entry: 'src/index.ts',
        },
        minify: false, // disable minify for framer (minified build has react-reconciler error)
        clean: true,
        external: ['react', 'framer', 'react-reconciler'],
        noExternal: ['@supabase/supabase-js'],
        esbuildPlugins: [
          glslLoader,
          commonjsPlugin(),
        ],
        // ...
      }
    })
  9. Check compatibility for Next.js 15 App Router

    main

    If you are using Next.js 15 with the App Router, you must use specific versions of @react-three/fiber and react to avoid structural incompatibilities with the App Router's vendored React 19 canary.

    Required Versions for Next 15 (App Router):

    • React: ^19.0.0
    • @react-three/fiber: ^9.0.0
    • three: >=0.158.0

    For other environments (Next 14, Pages Router, Vite, etc.), you can use React ^18 or ^19 with matching @react-three/fiber versions (8.x or 9.x). No special next.config aliases or transpilePackages entries are required if you follow these combinations.

  10. Reference ShaderGradient properties

    main

    The ShaderGradient component accepts several properties to control the mesh type, animation, colors, and camera behavior.

    Note: ShaderGradientCanvas also accepts props for pixelDensity, fov, envBasePath, GL overrides (preserveDrawingBuffer, powerPreference), and lazy-loading controls (lazyLoad, threshold, rootMargin).

    type MeshT = {
      type?: 'plane' | 'sphere' | 'waterPlane'
      animate?: 'on' | 'off'
      uTime?: number
      uSpeed?: number
      uStrength?: number
      uDensity?: number
      uFrequency?: number
      uAmplitude?: number
      range?: 'enabled' | 'disabled' | string
      rangeStart?: number
      rangeEnd?: number
      loop?: 'on' | 'off'
      loopDuration?: number
      positionX?: number
      positionY?: number
      positionZ?: number
      rotationX?: number
      rotationY?: number
      rotationZ?: number
      color1?: string
      color2?: string
      color3?: string
      reflection?: number
      wireframe?: boolean
      shader?: string
      rotSpringOption?: any
      posSpringOption?: any
    }
    
    type GradientT = MeshT & {
      control?: 'query' | 'props'
      isFigmaPlugin?: boolean
      smoothTime?: number
      cAzimuthAngle?: number
      cPolarAngle?: number
      cDistance?: number
      cameraZoom?: number
      lightType?: '3d' | 'env'
      brightness?: number
      envPreset?: 'city' | 'dawn' | 'lobby'
      grain?: 'on' | 'off'
      grainBlending?: number
      zoomOut?: boolean
      toggleAxis?: boolean
      hoverState?: string
      enableTransition?: boolean
      enableCameraUpdate?: boolean
      urlString?: string
      onCameraUpdate?: (updates: Partial<GradientT>) => void
    }