適用業(yè)務(wù)場景:
- 視頻截圖搀菩、視頻捕捉螃成、視頻快照旦签;
- 截取視屏第一幀,用作視頻封面展示寸宏;
實現(xiàn)思路:
- 主要通過canvas完成該功能顷霹;
- 通過drawImage將視頻寫入canvas;
- 通過video.currentTime設(shè)置視頻開始時間击吱;
- 通過canvas.toDataURL將canvas內(nèi)容輸出base64;
window.devicePixelRatio在<canvas>中更正分辨率遥昧;
完整代碼如下:
/**
* 視頻截圖
* @param {string} videoInfo.url - 視頻鏈接
* @param {string} videoInfo.progress - 視頻截取的秒數(shù)
* @author juehm
* @returns {Promise.resolve(base64)}
*/
const videoSnapshot = (videoInfo) => {
return new Promise((resolve, reject) => {
const video = document.createElement('video')
video.currentTime = videoInfo.progress //截取第幾秒
video.setAttribute('crossOrigin', 'anonymous') //解決資源跨域問題
video.setAttribute('src', videoInfo.url) //資源鏈接
// 當媒介數(shù)據(jù)已加載時運行的腳本覆醇。
video.addEventListener('loadeddata', function () {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const ratio = window.devicePixelRatio // 設(shè)備像素比(更正分辨率)
canvas.width = video.videoWidth * ratio
canvas.height = video.videoHeight * ratio
ctx.drawImage(video, 0, 0, canvas.width, canvas.height) //繪制圖片
resolve({
base64: canvas.toDataURL('image/png') // 輸出base64
})
})
video.addEventListener('error', function (event) {
reject({
msg: '視頻資源異常'
})
})
})
}
videoSnapshot({ url: './cat.mp4', progress: 1 }).then(({base64}) => {
console.log(base64);
}).catch((err) => {
console.log(err);
})