2013-04-26 143 views
1

我使用以下函數進行縮放和翻譯,並調整瀏覽器窗口的大小。但是,當窗口大小改變時,我想要保存寬高比(現在部分視頻被切斷),就像媒體播放器處理窗口大小調整一樣。響應式HTML5視頻+畫布

/** 
* This function is called when 'resize' event occur, it simply changes the way 
* <canvas> and <video> are displayed by browser using few CSS3 techniques. 
* @return none 
*/ 
    function resize() { 

     var w = 0; 
     var h = 0; 

     if (!window.innerWidth) { 
      if (!(document.documentElement.clientWidth == 0)) { 
       w = document.documentElement.clientWidth; 
       h = document.documentElement.clientHeight; 
      } else { 
       w = document.body.clientWidth; 
       h = document.body.clientHeight; 
      } 
     } else { 
      w = window.innerWidth; 
      h = window.innerHeight; 
     } 

     var cw = w; 
     var ch = h; 

     var aspect = videoWidth/videoHeight; 

     if (w/h > aspect) { 
      ch = cw/aspect; 
     } else { 
      cw = ch * aspect; 
     } 

     scalew = cw/videoWidth; 
     scaleh = ch/videoHeight; 

     dx = Math.round((w - cw)/2); 
     dy = Math.round((h - ch)/2); 

     var translateXForm = "translate(" + dx + "px," + dy + "px)"; 
     var scaleXForm = "scale(" + scalew + "," + scaleh + ")"; 
     var transform = translateXForm + " " + scaleXForm; 
     var style = 
     "-webkit-transform:" + transform + ";" + 
     "-moz-transform:" + transform + ";" + 
     "-ms-transform:" + transform + ";" + 
     "-o-transform:" + transform + ";" + 
     "transform:" + transform; 

     canvas.setAttribute("style", style); 
     video.setAttribute("style", style); 

    } 

回答

1

用JavaScript來做並不是必要的,我們可以用純CSS實現這個!

只需設置下列樣式的視頻標籤:

video { 
    height: auto; 
    width: 100%; 
} 

這將讓你的寬高比當調整窗口大小

DEMO

+0

謝謝!它工作正常