canvid.js

canvid is a tiny dependency free library for playback of relatively short videos on canvas elements.

Demo

We created the sprite for this demo with the tools descriped below. The sprite has about 700kb.

GIF Comparison

These are the same frames converted to a GIF. The GIF has about 4.9mb.

The GIF was created with these commands:

ffmpeg -i myvideo.mp4 -vf scale=375:-1 -r 5 frames/%04d.png
convert -loop 0 -delay 5 -colors 75 frames/*.png -fuzz "40%" output.gif

Installation

npm

npm install --save canvid

git clone

git clone git@github.com:gka/canvid.git

Usage

You can use canvid.js with AMD, CommonJS and browser globals.


var canvidControl = canvid({
    selector : '.video',
    videos: {
        clip1: { src: 'clip1.jpg', frames: 38, cols: 6, loops: 1, onEnd: function(){
          console.log('clip1 ended.');
          canvidControl.play('clip2');
        }},
        clip2: { src: 'clip2.jpg', frames: 43, cols: 6, fps: 24 }
    },
    width: 500,
    height: 400,
    loaded: function() {
        canvidControl.play('clip1');
        // reverse playback
        // canvidControl.play('clip1', true);
    }
});
        

If you want to use canvid with [React](https://facebook.github.io/react/) you can check this simple [react + canvid demo](http://codepen.io/moklick/pen/eJgbaL) to see how it works.

Options

Methods

The canvid function returns an object to control the video:

var canvidControl = canvid(canvidOptions);

play
Plays video of the passed videoKey. The parameters isReverse (default: false) and fps (default: 15) are optional.

canvidControl.play(videoKey [,isReverse, fps]);

pause
Pause current video.

canvidControl.pause();

resume
Resume current video.

canvidControl.resume();

destroy
Stops video and removes the canvas of the current canvid element from the DOM.

canvidControl.destroy();

isPlaying
Returns true or false whether the video is playing or not.

canvidControl.isPlaying();

getCurrentFrame
Returns the current frame number.

canvidControl.getCurrentFrame();

setCurrentFrame
Sets the current frame number.

canvidControl.setCurrentFrame(0);

How to convert your video to a JPG sprite

First, convert you video into single frames using ffmpeg:

ffmpeg -i myvideo.mp4 -vf scale=375:-1 -r 5 frames/%04d.png

Then, use ImageMagicks montage to stich all the frames into one big image:

montage -border 0 -geometry 375x -tile 6x -quality 60% frames/*.png myvideo.jpg

Is canvid responsive?

Yes it is, thanks to a nice little trick. Regardless of what width and height parameters you set in the canvid constructor, you can use style="width:100%" on the canvas element and it will get scaled to the outer container and preserve its original aspect ratio.

.canvid {
  width: 100%;
}

Contributors