0

我正在尝试使用带有此代码的画布在浏览器中从 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() 是异步的,因此,理论上,它应该让画布在跳转到下一行之前被绘制。

关于如何解决这个问题的任何想法?谢谢。

4

1 回答 1

0

经过几个小时的斗争,我终于想出了一个基于“寻找”事件的解决方案。为此,必须完全加载视频:

代码如下:

        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 事件在某些版本的特定浏览器中可能有问题。

希望这对任何人都有用。如果有人提出更清洁、更好的解决方案,很高兴看到它。

于 2012-07-27T12:05:56.913 回答