等到视频加载以捕获快照作为图像

Wait until video loads to capture snapshot as image

我正在编写一个脚本,该脚本将拍摄 mp4 视频并创建第一帧的快照。这样做的目的是一些移动浏览器不会在加载时播放 mp4。它将显示带有播放按钮的 mp4。因此,创建快照将是移动设备的一个很好的后备方案。

我已经有了一个基本的代码片段,它在 70% 的时间里都能正常工作。但是,当它不起作用时,我认为我在尝试使用脚本时遇到了问题从缓存的视频中拍摄快照,或者它试图在视频完全加载之前捕获。有人对如何做到 100% 有建议吗?我已经尝试推迟代码行以等待所有内容加载,但有时它不起作用......有点帮助的是添加一个小的 setTimeOut...

( function( window, $ ) {

const document = window.document;

const ImgSnapshot = (el) => {
    //setup variables
    const $el    = $(el);
    const video = $el.find(".wave-animation__container").get(0);

    $(video).ready( () => {

        setTimeout(() => {

            function createCanvas(){


                //create a canvas obj
                let canvas = document.createElement("canvas");
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                canvas.getContext('2d')
                    .drawImage(video, 0, 0, canvas.width, canvas.height);

                //wait until we have the canvas object captured
                return $.Deferred().resolve( canvas ).promise();
            }

            createCanvas().done( ( canvas ) => {
                   //create an image element to append
                   let img = document.createElement("img");
                   img.src = canvas.toDataURL();
                   img.classList.add('hide-for-medium', 'snapshot');

                   $el.append(img);

                   video.classList.add( 'show-for-medium' );
               });
           }, 150);



       });

   };


    $(document).ready(function(){
        $('.js-wave-animation').each(function(){
            new ImgSnapshot(this);
        });

    });

} )( window, jQuery );

对于这个问题我有不同的方法。与其使用 deferred 对象来检查视频是否已加载,不如使用 video

media events
<video width="400" controls id="myvideo">
    <source src="" type="video/mp4">
</video>
<script type="text/javascript">
    var jqvideo = $("#myvideo");
    var video = jqvideo[0];
    video.addEventListener("loadeddata", function() { 
        console.log("loaded");
        let canvas = document.createElement("canvas");
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        let img = document.createElement("img");
        img.src = canvas.toDataURL();
        $("body").append(img);
    }, true);
    jqvideo.find("source").attr("src", "yourvideourl.mp4");
</script>