简体   繁体   English

使用视频循环绘制画布

[英]Draw Canvas with video loop

I loop over a part of a HTML video and simultaneously draw a Canvas with the current frame of the video. 我在HTML视频的一部分上循环播放,并同时用视频的当前帧绘制一个Canvas。 When the Videos starts over, there is always 1 gray frame at the canvas. 当视频重新开始时,画布上始终有1个灰色框。 If the loop region is long, its not a big problem, but for my needs these regions are maybe 0.5 seconds and then the canvas starts to flicker if you loop over and over again. 如果循环区域很长,那么这不是什么大问题,但是对于我的需求,这些区域可能是0.5秒,如果您一遍又一遍地循环,画布就会开始闪烁。

When drawing the canvas, I also tried different video properties (ended, loop, networkState, readyState) - doesnt help 绘制画布时,我还尝试了不同的视频属性(结束,循环,networkState,readyState)-没有帮助

I provided a jsfiddle to show you my problem. 我提供了一个jsfiddle来向您展示我的问题。 (just press play at the video) https://jsfiddle.net/Lz17fnf3/2/ (只需在视频上按播放即可) https://jsfiddle.net/Lz17fnf3/2/

$('#v').on('timeupdate', function () {

    if ($('#v')[0].currentTime > 2) {//Loop for one second
        $('#v')[0].currentTime = 1;
    }

    var $this = $('#v')[0]; //cache
    (function loop() {
        if (!$this.paused && !$this.ended) {
            drawCanvas();
            setTimeout(loop, 1000 / 25); // drawing at 25fps
        }
    })();
});


function drawCanvas() {
    var elem = document.getElementById('c');
    var c = elem.getContext('2d');
    var v = $('#v')[0];
    $('#c').attr('width', v.videoWidth);
    $('#c').attr('height', v.videoHeight);
    if (v.readyState == 4) {
        c.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, v.videoWidth, v.videoHeight);
    }
}

The reason it flickers is because when you assign the width or height to a canvas element, this action resets the entire context of the canvas, most likely that is causing the blank frame. 闪烁的原因是,当您将widthheight分配给画布元素时,此操作将重置画布的整个上下文,这很可能导致空白帧。 Try moving all the canvas/context definitions outside the drawCanvas . 尝试将所有画布/上下文定义drawCanvas之外。

Something like: 就像是:

var elem = document.getElementById('c');
var c = elem.getContext('2d');
var v = $('#v')[0];

// In order to set the canvas width & height, we need to wait for the video to load.
function init() {
    if (v.readyState == 4) {
        $('#c').attr('width', v.videoWidth);
        $('#c').attr('height', v.videoHeight);
    } else {
        requestAnimationFrame(init);
    }
}

init();

$('#v').on('timeupdate', function () {
    if ($('#v')[0].currentTime > 2) { //Loop for one second
        $('#v')[0].currentTime = 1;
    }

    var $this = $('#v')[0]; //cache
    (function loop() {
        if (!$this.paused && !$this.ended) {
            drawCanvas();
            setTimeout(loop, 1000 / 25); // drawing at 25fps
        }
    })();
});

function drawCanvas() {
    c.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, v.videoWidth, v.videoHeight);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM