最近在作手機端上面播放視頻的項目,可是在安卓上面,video的播放是脫離頁面,置於最頂層的,因此帶來了不少問題,爲了解決這個問題,查看了多方資料,寫了下面簡單的demo,方便之後使用。javascript
下面就是運用canvas重繪video視頻。css
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=640,user-scalable=no"/> <title>X5內核瀏覽器video自動全屏解決辦法-canvas</title> <style> *{ margin: 0; padding: 0; } html,body{ width: 100%; height: 100%; overflow:hidden!important; } .content{ position: absolute; width: 100%; height: 1136px; top: 50%; transform: translate3d(0, -50%, 0); } #play{ position: absolute; top: 50%; left: 50%; transform: translate3d(-50%, -50%, 0); width: 100px; height: 100px; line-height: 100px; font-size: 28px; border: 1px solid #000; color: #000; text-align: center; border-radius: 50%; } #video{ position:absolute; left:50%; transform: translate3d(-50%,0,0); width: 100%; height: 100%; object-fit: cover; object-position: center center; display:none; } #myCanvas{ display: block; } </style> </head> <body> <div class="content"> <div id="play">播放</div> <video id="video" x5-playsinline="true" playsinline="true" webkit-playsinline="true" x5-video-player-type="h5" x5-video-player-fullscreen="true" src="movie.mp4" preload></video> <canvas id="myCanvas"> Your browser does not support the HTML5 canvas tag. </canvas> </div> <script type="text/javascript"> var v = document.getElementById('video'); var c = document.getElementById('myCanvas'); var ctx = c.getContext('2d'); document.getElementById("myCanvas").width = 640; document.getElementById("myCanvas").height = 1136; var cwidth = document.getElementById('myCanvas').offsetWidth; var cheight = document.getElementById('myCanvas').offsetHeight; // 初始化定時器 var i=null; document.getElementById("play").addEventListener("click",function(){ document.getElementById('video').play() }); // 播放 v.addEventListener("play", function() { document.getElementById("play").style.cssText = " display:none "; var i = window.setInterval(function() { ctx.drawImage(v, 0, 0, cwidth, cheight); }, 20); // 每0.02秒畫一張圖片 }, false); // 暫停 v.addEventListener("pause", function() { window.clearInterval(i); // 暫停繪畫 }, false); // 結束 v.addEventListener("ended", function() { clearInterval(i); }, false); </script> </body> </html>