color4bg

repository·main·Indexed 22 days ago

https://github.com/winterx/color4bg.js

A high-performance library for generating dynamic, abstract, and visually stunning WebGL-based background animations for web pages. It provides a core JavaScript package and a dedicated React component (@color4bg/react) supporting various styles such as aesthetic-fluid, abstract-shape, and chaos-waves. Users can customize backgrounds using hexadecimal colors, random seeds, and style-specific options.

Tokens
9.6K
Snippets
38
Records
44
Agent score
74%

What's inside color4bg

  1. Understand the OGL library structure

    main

    OGL is modular and split into three main components to keep the footprint small:

    1. Math: An extension of gl-matrix providing instancable classes that extend Array. It can be used independently.
    2. Core: The essential WebGL abstraction layer. It includes:
      • Geometry.js
      • Program.js
      • Renderer.js
      • Camera.js
      • Transform.js
      • Mesh.js
      • Texture.js
      • RenderTarget.js
    3. Extras: Additional layers of abstraction for advanced functionality, kept separate from the core to prevent bloat.
  2. Use the Color4Bg component

    main

    The Color4Bg component automatically mounts a WebGL canvas to its parent container. To use it, place the component inside a container that has a defined width and height. The component will automatically apply position: relative to the parent if no position is set.

    To ensure content appears above the background, wrap your content in a div with position: relative and a higher zIndex.

    import { Color4Bg } from '@color4bg/react'
    
    function App() {
      return (
        <div style={{ width: '100vw', height: '100vh', position: 'relative' }}>
          <Color4Bg style="aesthetic-fluid" loop={true} />
          <div style={{ position: 'relative', zIndex: 1 }}>
            <h1>Your Content</h1>
          </div>
        </div>
      )
    }
  3. Use color4bg in vanilla JavaScript

    main

    To use color4bg in a standard JavaScript environment, import a specific background class (e.g., AestheticFluidBg) and instantiate it with a configuration object. The dom option specifies the ID of the element where the background should be appended (do not include the # prefix).

    import { AestheticFluidBg } from "color4bg"
    
    let colorbg = new AestheticFluidBg({
        dom: "box",
        colors: ["#D1ADFF", "#98D69B", "#FAE390", "#FFACD8", "#7DD5FF", "#D1ADFF"],
        seed: 1000,
        loop: true
    })
  4. Integrate color4bg with React

    main

    For React projects, use the @color4bg/react package which provides a <Color4Bg /> component. This component accepts props for styling and configuration.

    npm install @color4bg/react
    import { Color4Bg } from '@color4bg/react'
    
    function App() {
      return (
        <div style={{ width: '100%', height: '100vh', position: 'relative' }}>
          <Color4Bg 
            style="aesthetic-fluid"
            colors={["#D1ADFF", "#98D69B", "#FAE390", "#FFACD8", "#7DD5FF", "#D1ADFF"]}
            loop={true}
            seed={1000}
          />
          <h1>Your content here</h1>
        </div>
      )
    }
  5. Import OGL into your project

    main

    OGL can be imported in several ways depending on your environment:

    • Local files: Import from the source path.
    • Bundlers/Node Modules: Import directly from the package name.
    • CDN: Use jsdelivr, unpkg, or skypack. It is recommended to append a specific version (e.g., @x.x.x) when using a CDN to prevent breaking changes.
    // From local source
    import { ... } from './path/to/src/index.js';
    
    // From node modules (bundler)
    import { ... } from 'ogl';
    
    // From CDN
    import { ... } from 'https://cdn.jsdelivr.net/npm/ogl';
    import { ... } from 'https://unpkg.com/ogl';
    import { ... } from 'https://cdn.skypack.dev/ogl';
  6. Configure color4bg options

    main

    When instantiating a background class or using the React component, you can provide the following configuration options:

    KeyTypeDescription
    domstringId of DOM element where to append colorbg, no need to add "#"
    colorsArrayAn array of up to 6 hexadecimal color values
    seedNumberA Pseudo-random numerical value used to generate a consistent pattern
    loopBoolDetermines whether the background should animated looply or not
  7. Create a full-screen shader with custom geometry

    main

    For simpler use cases like full-screen effects, you can omit the Camera and Transform (scene graph). This example shows how to create a custom Geometry (a triangle covering the viewport) and use uniforms to pass time to a fragment shader.

    import { Renderer, Geometry, Program, Mesh } from 'ogl';
    
    {
        const renderer = new Renderer({
            width: window.innerWidth,
            height: window.innerHeight,
        });
        const gl = renderer.gl;
        document.body.appendChild(gl.canvas);
    
        // Triangle that covers viewport, with UVs that still span 0 > 1 across viewport
        const geometry = new Geometry(gl, {
            position: { size: 2, data: new Float32Array([-1, -1, 3, -1, -1, 3]) },
            uv: { size: 2, data: new Float32Array([0, 0, 2, 0, 0, 2]) },
        });
    
        const program = new Program(gl, {
            vertex: /* glsl */ `
                attribute vec2 uv;
                attribute vec2 position;
    
                varying vec2 vUv;
    
                void main() {
                    vUv = uv;
                    gl_Position = vec4(position, 0, 1);
                }
            `,
            fragment: /* glsl */ `
                precision highp float;
    
                uniform float uTime;
    
                varying vec2 vUv;
    
                void main() {
                    gl_FragColor.rgb = vec3(0.8, 0.7, 1.0) + 0.3 * cos(vUv.xyx + uTime);
                    gl_FragColor.a = 1.0;
                }
            `,
            uniforms: {
                uTime: { value: 0 },
            },
        });
    
        const mesh = new Mesh(gl, { geometry, program });
    
        requestAnimationFrame(update);
        function update(t) {
            requestAnimationFrame(update);
    
            program.uniforms.uTime.value = t * 0.001;
    
            // Don't need a camera if camera uniforms aren't required
            renderer.render({ scene: mesh });
        }
    }
  8. Dynamically update Color4Bg props

    main

    The Color4Bg component automatically updates when its props change. You can use React state to dynamically change colors, seed, loop, and options.

    import { useState } from 'react'
    import { Color4Bg } from '@color4bg/react'
    
    function MyComponent() {
      const [seed, setSeed] = useState(1000)
      const [colors, setColors] = useState(["#FF0000", "#00FF00"])
    
      return (
        <div className="container">
          <Color4Bg 
            style="abstract-shape"
            seed={seed}
            colors={colors}
            loop={true}
          />
          <button onClick={() => setSeed(Math.random() * 10000)}>
            Change Seed
          </button>
          <button onClick={() => setColors(["#0000FF", "#FFFF00"])}>
            Change Colors
          </button>
        </div>
      )
    }
  9. Render a spinning 3D cube

    main

    This example demonstrates a standard 3D scene setup using a Renderer, Camera, Transform (scene graph), Box geometry, and a Program with custom GLSL shaders.

    import { Renderer, Camera, Transform, Box, Program, Mesh } from 'ogl';
    
    {
        const renderer = new Renderer();
        const gl = renderer.gl;
        document.body.appendChild(gl.canvas);
    
        const camera = new Camera(gl);
        camera.position.z = 5;
    
        function resize() {
            renderer.setSize(window.innerWidth, window.innerHeight);
            camera.perspective({
                aspect: gl.canvas.width / gl.canvas.height,
            });
        }
        window.addEventListener('resize', resize, false);
        resize();
    
        const scene = new Transform();
    
        const geometry = new Box(gl);
    
        const program = new Program(gl, {
            vertex: /* glsl */ `
                attribute vec3 position;
    
                uniform mat4 modelViewMatrix;
                uniform mat4 projectionMatrix;
    
                void main() {
                    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
                }
            `,
            fragment: /* glsl */ `
                void main() {
                    gl_FragColor = vec4(1.0);
                }
            `,
        });
    
        const mesh = new Mesh(gl, { geometry, program });
        mesh.setParent(scene);
    
        requestAnimationFrame(update);
        function update(t) {
            requestAnimationFrame(update);
    
            mesh.rotation.y -= 0.04;
            mesh.rotation.x += 0.03;
    
            renderer.render({ scene, camera });
        }
    }