适用业务场景:
- 视频截图、视频捕捉、视频快照;
- 截取视屏第一帧,用作视频封面展示;
实现思路:
- 主要通过canvas完成该功能;
- 通过drawImage将视频写入canvas;
- 通过video.currentTime设置视频开始时间;
- 通过canvas.toDataURL将canvas内容输出base64;
window.devicePixelRatio在<canvas>中更正分辨率;
完整代码如下:
/**
* 视频截图
* @param {string} videoInfo.url - 视频链接
* @param {string} videoInfo.progress - 视频截取的秒数
* @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) //资源链接
// 当媒介数据已加载时运行的脚本。
video.addEventListener('loadeddata', function () {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const ratio = window.devicePixelRatio // 设备像素比(更正分辨率)
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);
})