直接贴代码
/**
* 截取视频画面
* @param {*} url 视频播放链接
* @param {*} width 画面的截取宽度
* @param {*} height 图片的截取高度
*/
export function cutVideoCover(url, width = 960, height = 540) {
return new Promise((reslove) => {
let video = document.createElement('video');
video.crossOrigin = 'anonymous'; //处理跨域
video.src = url;
video.width = width;
video.height = height;
video.preload = 'auto'; //预加载视频,以保证可稳定获取画面
video.currentTime = 1; //指定截取几秒处的帧
// video.autoplay = true;
// video.muted = true;
//当视频完成渲染
video.onloadeddata = () => {
let canvas = document.createElement('canvas');
canvas.width = video.width;
canvas.height = video.height;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height); //绘制canvas
let fileType = 'image/jpeg';
// 返回形式1:以url形式返回,需要配置接口上传
canvas.toBlob((blob) => {
let blobFile = new File([blob], randomNum(100000, 1000000) + '.jpg', { type: fileType }); //转成file格式
const params = new FormData();
params.append('file', blobFile);
//上传到接口转成图片链接
commonApi
.uploadFile(params)
.then((res) => {
if (res.code == 200000) {
reslove(res.msg);
}
})
.finally(() => {
video = null; //清除video元素
});
}, fileType);
//返回形式2:以base64格式返回。可直接用img标签展示
// const base64Url = canvas.toDataURL(fileType) //转为base64,返回
// resolve(base64Url)
};
});
}
调用
cutVideoCover(videoUrl).then((res) => {
console.log(res) //图片地址
});