Chroma key a video/image/canvas element in real time using the GPU. Based on work by Brian Chirls.
- Multiple key colors with adjustable tolerance
- Automatic background color detection and keying
- Designed for requestAnimationFrame (when used with video)
- Uses WebGL 2
- No dependencies
$ npm i gl-chromakey
source
: Source video, image or canvas element to keytarget
: Target canvas element on which to paint keyed image(s)
const GLChroma = require('gl-chromakey')
const video = document.getElementById('my-video')
const canvas = document.getElementById('my-canvas')
// set source video and target canvas elements
const chroma = new GLChroma(video, canvas)
Returns true if browser supports WebGL 2, else false.
Sets one or more key colors in RGB, replacing any prior settings. Calling without parameters clears all key colors.
key
: any of the following:- the string
'auto'
- array of color values like
[r, g, b]
(keys a single color with defaulttolerance
) - array of objects with properties:
color
(required): the string'auto'
or an array of color values like[r, g, b]
tolerance
: float ranged 0-1; allowed distance fromcolor
(default=0.3
)amount
: float ranged 0-1; strength of alpha effect (default=1.0
)
- the string
The auto
key color mode works by downsampling the source image, grabbing each corner pixel, and keying on the two pixels with the most similar color. It works best on video or images with simplistic backgrounds, and if the algorithm gets it wrong, can cause flickering in some cases.
Examples:
// detect background color (per-frame, works best with solid-ish backgrounds)
chroma.key('auto')
chroma.key({ color: 'auto', tolerance: 0.3 }) // equivalent
// a very greenscreen
chroma.key([0, 255, 0])
chroma.key({ color: [0, 255, 0], tolerance: 0.3 }) // equivalent
Re-paints current frame to canvas.
Updates frame from source element and paints to target canvas. The following excerpt shows its use with a video element and a requestAnimationFrame loop to update the video frames:
let frameId
// methods for render loop
startChroma = () => {
frameId = requestAnimationFrame(startChroma)
chroma.render()
}
stopChroma = () => cancelAnimationFrame(frameId)
// link to <video> element
video.addEventListener('play', startChroma)
video.addEventListener('pause', stopChroma)
video.addEventListener('ended', stopChroma)
Sets a new source video, image or canvas element to key.
el
: the new video/image/canvas element
Sets a new target canvas on which to paint keyed image(s). The context webgl2
will be used.
canvas
: the newHTMLCanvasElement
element