Kampos

repository·master·Indexed 41 days ago

https://github.com/wix-incubator/kampos

A tiny (~4KB) and fast WebGL-based effects compositor for applying filter effects and transitions to images, videos, and other media. Version 0.16.0 includes a core engine, Ticker for animation loops, noise generators, and a variety of built-in effects such as hueSaturation, duotone, and shapeTransition.

Tokens
3.6K
Snippets
15
Records
19
Agent score
98%

What's inside Kampos

  1. Import kampos and its components

    master

    You can import the full build containing the core engine, ticker, effects, and transitions, or import specific modules directly from the source files to reduce bundle size.

    // Import the default build
    import { Kampos, Ticker, effects, transitions } from 'kampos';
    
    // Or import specific modules directly from source
    import Kampos from './node_modules/kampos/src/kampos';
    import duotone from './node_modules/kampos/src/effects/duotone';
    import displacement from './node_modules/kampos/src/effects/displacement';
  2. Initialize Kampos with the Kampos class

    master

    The Kampos class is the main entry point for managing media sources and effect composition on a WebGL target. To use it, instantiate it with a configuration object containing a target (an HTMLCanvasElement) and an array of effects.

    Configuration Options (kamposConfig)

    • target: The HTMLCanvasElement to render onto.
    • effects: An array of effectConfig objects defining shaders and parameters.
    • plane: Configuration for the geometry segments (planeConfig).
    • fbo: Configuration for Framebuffer Objects (fboConfig).
    • ticker: An optional Ticker instance to manage the animation loop.
    • noSource: Boolean to indicate no media source will be used.
    • beforeDraw: Callback function run before each draw call. If it returns false, draw is skipped.
    • afterDraw: Callback function run after each draw call.
    • onContextLost: Callback when the WebGL context is lost.
    • onContextRestored: Callback when the WebGL context is restored.
    • onContextCreationError: Callback when WebGL context creation fails.
    import { Kampos, effects } from 'kampos';
    
    const target = document.querySelector('#canvas');
    const hueSat = effects.hueSaturation();
    const kampos = new Kampos({
      target,
      effects: [hueSat]
    });
  3. Basic usage of kampos to apply effects to media

    master

    To use kampos, create an instance of Kampos by providing a target (a <canvas> element) and an array of effects. Use setSource(media) to specify the input media (like a <video> or <img>) and play() to start the compositor.

    import { Kampos, effects } from 'kampos';
    
    const target = document.querySelector('canvas');
    const media = document.querySelector('video');
    
    // Create an effect and configure its properties
    const hueSaturation = effects.hueSaturation();
    hueSaturation.hue = 90;
    
    // Initialize Kampos with the target canvas and the effect list
    const kampos = new Kampos({ target, effects: [hueSaturation] });
    
    // Set the input media and start playback
    kampos.setSource(media);
    kampos.play();
  4. Configure shapeTransition options

    master

    The shapeTransition function accepts the following configuration options:

    OptionTypeDefaultDescription
    nbDividernumber50Number of shapes to divide the screen into.
    shapestring'circle'Shape of every grid cell. Use shapeTransition.CIRCLE, shapeTransition.SQUARE, or shapeTransition.DIAMOND.
    directionstring'xy'Direction of the transition. Use constants like shapeTransition.DIRECTION_TOP_LEFT, shapeTransition.DIRECTION_LEFT, etc.
    effectstring'transitionColor'Effect type. Use shapeTransition.COLOR_TRANSITION, shapeTransition.ALPHA_TRANSITION, or shapeTransition.APPEAR_ALPHA.
    enableBrightnessbooleanfalseEnable brightness effect.
    maxBrightnessnumber1Maximum brightness to use for the effect.
    enableColorbooleanfalseEnable overlay color effect.
    colorArray<number>[0.1, 0.1, 0.1]Background color for overlay color effect (RGB).
    progressnumber0Progress of the transition (0.0 to 1.0).
    shapeBordernumber0.15Border size of the shape.
  5. Set a media source using setSource()

    master

    Use setSource() to provide the media (image, video, canvas, etc.) that will be processed by the effects.

    Supported Source Types

    You can pass:

    • ArrayBufferView | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | ImageBitmap
    • A kamposSource object: { media, width, height, shouldUpdate? }

    Behavior

    • If the source is a HTMLVideoElement or HTMLCanvasElement, shouldUpdate defaults to true.
    • The target canvas is automatically resized to match the source dimensions.
    • If skipTextureCreation is false (default), textures are created immediately.
    const media = document.querySelector('#video');
    kampos.setSource(media);
  6. Clean up resources with destroy()

    master

    Call destroy() to stop the animation loop and free all WebGL resources (textures, framebuffers, etc.).

    • destroy(false) (default): Stops the loop, destroys WebGL resources, and removes event listeners for context loss/creation errors. This effectively resets the instance.
    • destroy(true): Keeps the source state (media, dimensions) cached so the instance can be re-initialized more easily.
    kampos.destroy();
  7. Control the animation loop with play() and stop()

    master

    Kampos provides methods to manage the rendering loop.

    play(beforeDraw, afterDraw)

    Starts the animation loop.

    • If a ticker was provided in the constructor, Kampos is added to that ticker.
    • If no ticker was provided, it uses window.requestAnimationFrame internally.
    • You can optionally pass beforeDraw and afterDraw functions to override or set the lifecycle callbacks.

    stop()

    Stops the animation loop. If a ticker is used, Kampos is removed from it. If using requestAnimationFrame, the loop is cancelled.

    // Start playing
    kampos.play((time) => {
      // logic before draw
    }, (time) => {
      // logic after draw
    });
    
    // Stop playing
    kampos.stop();
  8. ShapeTransition effect properties and setters

    master

    The object returned by shapeTransition() provides several properties and setters to control the effect dynamically during runtime:

    • disabled: Boolean. Enables or disables the effect.
    • progress: Number (0.0 to 1.0). Controls the transition progress.
    • to: The target media source (e.g., HTMLVideoElement, HTMLCanvasElement, ImageBitmap, etc.) to transition into.
    • resolution: [width, height]. Sets the resolution of the media source.
    • dividerCount: Number of shapes in the grid.
    • shapeBorder: Border size of the shapes.
    • direction: The direction of the transition (e.g., shapeTransition.DIRECTION_TOP).
    • effect: The effect type (e.g., shapeTransition.ALPHA_TRANSITION).
    • brightnessEnabled: Boolean. Enables/disables brightness.
    • maxBrightness: Maximum brightness value.
    • color: [r, g, b] array. Sets the overlay color.
    • overlayColorEnabled: Boolean. Enables/disables overlay color.
  9. Use the shapeTransition effect

    master

    The shapeTransition function creates a WebGL effect descriptor that allows transitioning between two media sources using a grid of shapes (circles, squares, or diamonds). The transition can be controlled via direction, effect type (color, alpha, or appear alpha), and various visual parameters like brightness and overlay color.

    To use it, call shapeTransition(options) where options is an object containing your desired configuration. The returned object is a descriptor that can be used within the Kampos compositor system.

    import shapeTransition from './src/transitions/shape.js';
    
    const effect = shapeTransition({
        nbDivider: 50,
        shape: shapeTransition.CIRCLE,
        direction: shapeTransition.DIRECTION_TOP_LEFT,
        effect: shapeTransition.COLOR_TRANSITION,
        enableBrightness: true,
        maxBrightness: 1,
        enableColor: true,
        color: [0.1, 0.1, 0.1],
        progress: 0,
        shapeBorder: 0.15
    });
  10. Define effect configurations

    master

    An effect is defined by the effectConfig type. It specifies the shaders and the data (uniforms, attributes, textures) required for the effect to run.

    effectConfig Structure

    • vertex: shaderConfig for the vertex shader.
    • fragment: shaderConfig for the fragment shader.
    • attributes: Array of Attribute objects.
    • uniforms: Array of Uniform objects.
    • varying: Object defining varying variables.
    • textures: Array of textureConfig objects.
    // Example of the structure required for an effect
    const effect = {
      vertex: { main: '...' },
      fragment: { main: '...' },
      attributes: [],
      uniforms: [],
      varying: {},
      textures: []
    };
  11. ShapeTransition direction and effect constants

    master

    Use these constants to specify the direction and effect type for shapeTransition:

    Directions:

    • shapeTransition.DIRECTION_TOP_LEFT (1)
    • shapeTransition.DIRECTION_TOP (2)
    • shapeTransition.DIRECTION_TOP_RIGHT (3)
    • shapeTransition.DIRECTION_LEFT (4)
    • shapeTransition.DIRECTION_CONSTANT (5)
    • shapeTransition.DIRECTION_RIGHT (6)
    • shapeTransition.DIRECTION_BOTTOM_LEFT (7)
    • shapeTransition.DIRECTION_BOTTOM (8)
    • shapeTransition.DIRECTION_BOTTOM_RIGHT (9)

    Effects:

    • shapeTransition.COLOR_TRANSITION (1): Transition using a color overlay.
    • shapeTransition.ALPHA_TRANSITION (2): Transition using transparency.
    • shapeTransition.APPEAR_ALPHA (3): Transition from a transparent canvas to the source media.