同步运行画布动画和视频

问题描述 投票:1回答:1

我想在两个视频的顶部使用window.requestanimationframe()方法为画布上的内容制作动画(例如,突出显示两个视频中的重要内容)。当前,动画运行,然后,视频开始一起播放。那么如何才能同时执行所有内容(视频和画布动画)?

class Animation {

    constructor(canvas, data) {
        this.canvas = document.getElementById(canvas);
        this.ctx = this.canvas.getContext('2d');
        this.data = data;
        this.start = 0;
        this.counter = 0;
        this.running = false;

        this.draw = function(){
            console.log(this);
            console.log("Draw");
            if(!document.querySelector('video').playing){
                // init
                this.ctx.clearRect(0, 0, 300, 300); // clear canvas

                // get data
                var in_video_data = this.data['in_video'];

                // draw CircleLineTimeSeries
                for (var i=0; i<in_video_data.length; i++){
                    var item = in_video_data[i];
                    // if counter in phase intervall
                    if (this.counter >= item['start'] && this.counter <= item['end']){
                        console.log(item);
                        if (item['object'] == 'CircleLineTimeSeries'){
                            this.visualizeCircleLine(item['raw_kps'][0][this.counter],
                                                     item['raw_kps'][1][this.counter]);
                        }
                    }
                }

                // Increase time variable
                this.counter += 1;

            }
            if (this.running){
                window.requestAnimationFrame(this.draw.bind(this));
            }
        }
    }


    visualizeCircleLine(kps0, kps1){
        this.ctx.beginPath();
        this.ctx.moveTo(kps0[0], kps0[1]);
        this.ctx.lineTo(kps1[0], kps1[1]);
        this.ctx.stroke();
    }

    play(){
        this.running = true;
        window.requestAnimationFrame(this.draw.bind(this));
    }

    pause(){
        this.running = false;
    }
}

用于运行视频和画布动画的代码:

/**
* Event handler for play button
*/
function playPause(){
    if (running){
        running = false;
        animation.pause();
        video0.pause();
        video1.pause();
    } else {
        running = true;
        animation.play();
        video0.play();
        video1.play();
    }
}

提前谢谢您:)

javascript canvas html5-canvas html5-video requestanimationframe
1个回答
1
投票

正如@Kaiido指出的,您必须收听视频当前时间的更新。有相应的媒体事件-timeupdate。此外,在显示动画时,您应该具有视频关键帧的列表。每当触发timeupdate事件时,请检查到达某个关键帧的当前时间,如果是,则通知timeupdate回调以通过某个共享变量来运行动画。

© www.soinside.com 2019 - 2024. All rights reserved.