2012-07-26 71 views
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()是異步的,因此理論上應該讓畫布在跳到下一行之前進行繪製。

有關如何解決此問題的任何想法? 謝謝。

回答

0

經過數小時的戰鬥後,我終於想出了一個基於「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事件可能是越野車在某些版本的特定瀏覽器中。

希望這對任何人都有用。如果有人想出一個更清潔,更好的解決方案,很高興看到它。