Skip to content

Instantly share code, notes, and snippets.

@westc
Last active October 2, 2019 21:48
Show Gist options
  • Save westc/f6de681820d78df64c01e10bfd03f985 to your computer and use it in GitHub Desktop.
Save westc/f6de681820d78df64c01e10bfd03f985 to your computer and use it in GitHub Desktop.
A function to grab the frame at a specific point within a video.
function getVideoImage(path, secs, callback) {
var me = this, video = document.createElement('video');
video.onloadedmetadata = function() {
if ('function' === typeof secs) {
secs = secs(this.duration);
}
this.currentTime = Math.min(Math.max(0, (secs < 0 ? this.duration : 0) + secs), this.duration);
};
video.onseeked = function(e) {
var canvas = document.createElement('canvas');
canvas.height = video.videoHeight;
canvas.width = video.videoWidth;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
var img = new Image();
img.src = canvas.toDataURL();
callback.call(me, img, this.currentTime, e);
};
video.onerror = function(e) {
callback.call(me, undefined, undefined, e);
};
video.src = path;
}
@kjantzer
Copy link

kjantzer commented Oct 2, 2019

Here's a slightly improved version ready to be imported with webpack or parceljs

// originally from: https://gist.github.com/westc/f6de681820d78df64c01e10bfd03f985
export default (path, {
    secs=.5,
    width=null
}={}) => {

    return new Promise((resolve,reject)=>{

        let video = document.createElement('video');

        video.onloadedmetadata = function() {
            
            if('function' === typeof secs )
                secs = secs(this.duration);
                
            else if( secs > 0 && secs < 1)
                secs = secs * this.duration

            this.currentTime = Math.min(Math.max(0, (secs < 0 ? this.duration : 0) + secs), this.duration);
        };

        video.onseeked = function(e) {
            let canvas = document.createElement('canvas');
            let ratio = video.videoWidth / video.videoHeight;
            
            width = width || video.videoWidth;
            canvas.width = width;
            canvas.height = width / ratio;
            
            let ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            
            resolve(canvas.toDataURL())
        };
        
        video.onerror = function(e) {
            reject()
        };

        video.src = path;

    })

}
import videoScreenshot from 'file-above'

src = await videoScreenshot(path)
src = await videoScreenshot(path, {secs:0.25}) // 25% of duration

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment