Skip to content

Custom Effects

Caleb Sacks edited this page Aug 7, 2020 · 1 revision

Vidar comes with a set of predefined effects, but you can also create your own.

Hello World

/** Draws  a red rectangle filling the entire layer */
class HelloWorld extends vd.effect.Base {
  apply(target) {
    // `target` is the layer or movie that the effect is being applied to.
    // Each layer and movie has a canvas `canvas` and a canvas context, `cctx`.
    target.cctx.fillStyle = 'red';
    target.cctx.fillRect(0, 0, target.canvas.width, target.canvas.height);
  }
}

Then add this to a layer or movie:

layer.addEffect(new HelloWorld());

The vd.effect.Base is the base class for all visual effects. The apply method is called every frame by the movie to use the effect. target is the layer or movie to which the effect belongs.

Shaders

You can also write GLSL effects:

class SwapChannels extends vd.effect.Shader {
  constructor() {
    super(`
      precision mediump float;

      // the original image
      uniform sampler2D u_Source;
      // the texture coord
      varying highp vec2 v_TextureCoord;

      void main() {
        vec4 source = texture2D(u_Source, v_TextureCoord);
        gl_FragColor = source.bgra;
      }
    `);
  }
}

If you need to pass arguments to your shader, register them in the constructor and then set them as properties of the effect. If you register a property foo, you can access it in the shader as a uniform u_Foo.

Here is the built-in brightness effect:

class Brightness extends vd.effect.Shader {
  constructor (brightness = 0.0) {
    super(`
      precision mediump float;

      uniform sampler2D u_Source;
      uniform float u_Brightness;

      varying highp vec2 v_TextureCoord;

      void main() {
          vec4 color = texture2D(u_Source, v_TextureCoord);
          vec3 rgb = clamp(color.rgb + u_Brightness / 255.0, 0.0, 1.0);
          gl_FragColor = vec4(rgb, color.a);
      }
    `, {
      // value: type
      brightness: '1f' // single float
    });
    this.brightness = brightness;
  }
}

![Before effect](images/Creating-Canvas-Effects.0.jpg) → ![After effect](images/Creating-Canvas-Effects.1.png)
Clone this wiki locally