PS:获取封面前提是浏览器要支持视频编码格式,不支持就不能通过该方式获取
读取视频封面:
let video = document.createElement("video");
video.src = videosrc;
video.currentTime= 10 // 可能出现黑屏,从10帧
video.muted = true; // 解决个别电脑获取到空图
video.autoplay = true; // 解决个别电脑获取到空图
video.preload = true; // 解决个别电脑获取到空图
video.addEventListener('loadeddata', async () => {
video.pause();
var canvas = document.createElement('canvas')
canvas.width = video.videoWidth
canvas.height = video.videoHeight
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
const cover = canvas.toDataURL('image/png')
console.log('图片base64是:',cover)
video.remove();
}}
base64转file:
const convertFile = base64 => {
let fileArray = base64.split(','),
fileType = fileArray[0].match(/:(.*?);/)[1],
bstr = atob(fileArray[1]),
n = bstr.length,
u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], '文件名', { type: fileType })
}
下载:
const buttonClick = (base64) => {
let file = convertFile(base64)
const node = document.createElement('a')
node.href = URL.createObjectURL(file)
node.download = file.name
node.click()
URL.revokeObjectURL(node.href)
document.body.appendChild(node)
document.body.removeChild(node)
}