利用canvas的drawImage() API,第一個參數傳video可以將視頻當前幀畫到畫布上,(這里示例是第一幀),
以下代碼需要注意:因為跨域限制,必須放到web服務器上運行(比如localhost),如果直接是在硬盤上的文件系統打開是不行(file://...)的。
另外,這里示例上用的是本地存了一個視頻文件,實際項目時如果腳本和視頻不在同一個域還是會發生跨域問題,參數另一篇帖子。
getVideoCover() 就是獲取視頻的函數,可以直接調用。
<!DOCTYPE html> <html> <body> <img id="img"> <script> function getVideoCover(url, width = null, height = null) { return new Promise((resolve, reject) => { const canvas = document.createElement('canvas'); const video = document.createElement('video'); document.body.appendChild(video); video.setAttribute('crossOrigin', 'anonymous'); canvas.width = width ? width : video.clientWidth; canvas.height = height ? height : video.clientHeight; video.style.height = '0'; video.onloadeddata = (() => { setTimeout(() => { canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height); let b64 = canvas.toDataURL('image/png'); document.body.removeChild(video); resolve(b64); }, 100); }); video.setAttribute('src', url); }); } getVideoCover('./videoplayback.mp4', 200, 150).then((base64) => { document.getElementById('img').setAttribute('src', base64); }); </script> </body> </html>