- 將視頻隱藏正常播放
- 將播放取到畫面使用setInterval循環在畫布上顯示畫面,由於 1s 差很少25-30幀,選擇每40ms循環一次
- 繪畫中的大小,寬度等於100%,高度垂直居中。x 爲 0,y 爲(canvas.height - video.height)/2/canvas縮放倍數
- 視頻暫停或者播放結束後,清除定時器
html代碼html
<video id="main-video" playsinline="true" webkit-playsinline="true" x5-playsinline="true" x5-video-orientation="portraint" x5-video-player-fullscreen="true" x5-video-player-type="h5" style="display: none"> <source id="js-video-source" src="<%=detail.videoUrl || ''%>" ></source>'; </video> <canvas style="width: 100%; height:100%" id="canvas"></canvas>
js代碼web
function renderCanvas () { let $canva, ctx, $video, setInter; $canva =$('#canvas'); $video = $("#main-video"); ctx = $canva[0].getContext('2d'); $canva.style.width = $canva.parents().width() / 2; $canva.style.height = $canva.parents().height() / 2; $video[0].play(); render(); setInter = setInterval(r => { render(); }, 40) function render () { ctx.drawImage($video[0], 0, (canvas.height - video.height)/2/2, video.width(), video.height()); } // 視頻播放結束 $video[0].on('ended', function () { clearInterval(setInter); }); // 視頻被暫停 $video[0].on('pause', function () { clearInterval(setInter); }); }