如何从组件<video> </video>获取帧

时间:2019-03-23 14:24:48

标签: javascript html video

我想从javascript中的HTML <video></video>组件中获取帧,以便可以对其进行处理,然后输出到画布上

1 个答案:

答案 0 :(得分:0)

看看下面的codepen:Demo

var videoId = 'video';
    var scaleFactor = 0.25;
    var snapshots = [];

    /**
     * Captures a image frame from the provided video element.
     *
     * @param {Video} video HTML5 video element from where the image frame will be captured.
     * @param {Number} scaleFactor Factor to scale the canvas element that will be return. This is an optional parameter.
     *
     * @return {Canvas}
     */
    function capture(video, scaleFactor) {
        if (scaleFactor == null) {
            scaleFactor = 1;
        }
        var w = video.videoWidth * scaleFactor;
        var h = video.videoHeight * scaleFactor;
        var canvas = document.createElement('canvas');
        canvas.width = w;
        canvas.height = h;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, w, h);
        return canvas;
    }

    /**
     * Invokes the <code>capture</code> function and attaches the canvas element to the DOM.
     */
    function shoot() {
        var video = document.getElementById(videoId);
        var output = document.getElementById('output');
        var canvas = capture(video, scaleFactor);
        canvas.onclick = function() {
            window.open(this.toDataURL(image/jpg));
        };
        snapshots.unshift(canvas);
        output.innerHTML = '';
        for (var i = 0; i < 4; i++) {
            output.appendChild(snapshots[i]);
        }
    }

(function() {
  var captureit = document.getElementById('cit');
  captureit.click();
})();

将视频网址更改为:http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_60fps_normal.mp4,您将看到一个实时演示示例