捕获HTML5视频截图组

Capture group of HTML5 video screenshots

本文关键字:视频 HTML5 捕获      更新时间:2024-02-25

我正试图在浏览器中使用画布从HTML5视频中生成一组缩略图,代码如下:

        var fps = video_model.getFps(); //frames per second, comes from another script
        var start = shot.getStart(); //start time of capture, comes from another script
        var end = shot.getEnd(); //end time of capture, comes from another script
        for(var i = start; i <= end; i += 50){  //capture every 50 frames
            video.get(0).currentTime = i / fps;
            var capture = $(document.createElement("canvas"))
                .attr({
                    id: video.get(0).currentTime + "sec",
                    width: video.get(0).videoWidth,
                    height: video.get(0).videoHeight
                })
            var ctx = capture.get(0).getContext("2d");
            ctx.drawImage(video.get(0), 0, 0, video.get(0).videoWidth, video.get(0).videoHeight);
            $("body").append(capture, " ");
        }

捕获的数量是正确的,但问题是在Chrome中,所有的画布都显示为黑色,而在Firefox中,它们总是显示相同的图像。

也许问题是循环太快,无法绘制画布,但我读到.drawImage()是异步的,因此,理论上,它应该在跳到下一行之前绘制画布。

关于如何解决这个问题有什么想法吗?谢谢

经过数小时的斗争,我终于想出了一个基于"seeked"事件的解决方案。要做到这一点,视频必须完全加载:

代码如下:

        var fps = video_model.getFps(); //screenshot data, comes from another script
        var start = shot.getStart();
        var end = shot.getEnd();

        video.get(0).currentTime = start/fps; //make the video jump to the start

        video.on("seeked", function(){ //when the time is seeked, capture screenshot
            setTimeout( //the trick is in giving the canvas a little time to be created and painted, 500ms should be enough
                function(){
                    if( video.get(0).currentTime <= end/fps ){
                        var capture = $(document.createElement("canvas")) //create canvas element on the fly
                        .attr({
                            id: video.get(0).currentTime + "sec",
                            width: video.get(0).videoWidth,
                            height: video.get(0).videoHeight
                        })
                        .appendTo("body");
                        var ctx = capture.get(0).getContext("2d"); //paint canvas
                        ctx.drawImage(video.get(0), 0, 0, video.get(0).videoWidth, video.get(0).videoHeight);
                        if(video.get(0).currentTime + 50/fps > end/fps){
                            video.off("seeked"); //if last screenshot was captured, unbind
                        }else{
                              video.get(0).currentTime += 50/fps; //capture every 50 frames
                        }

                    }
                }
                , 500); //timeout of 500ms

        });

这在Chrome和Firefox中对我起到了作用,我读到在某些版本的特定浏览器中,seeked事件可能会出现错误。

希望这对任何人都有用。如果有人能想出一个更清洁、更好的解决方案,那就太好了。