獲取視頻的尺寸,播放時長
loadVideo = function(file) {
return new Promise(function(resolve, reject) {
const videoElem = document.createElement('video')
const dataUrl = URL.createObjectURL(file)
// 當前幀的數據是可用的
videoElem.onloadeddata = function() {
resolve(videoElem)
}
videoElem.onerror = function() {
reject('video 後臺加載失敗')
}
// 設置 auto 預加載數據, 否則會出現截圖爲黑色圖片的情況
videoElem.setAttribute('preload', 'auto')
videoElem.src = dataUrl
})
}
//獲取視頻時長, 尺寸
loadVideo(file).then(video => {
const duration = video.duration
const witth = video.videoWidth
const height = videoHeight
})
其中file
爲視頻的文件對象,可使用input[file]
進行獲取
獲取視頻的第一幀圖片
loadVideo(file).then(video => {
const canvasElem = document.createElement('canvas')
const { videoWidth, videoHeight } = videoElem
canvasElem.width = videoWidth
canvasElem.height = videoHeight
canvasElem.getContext('2d').drawImage(videoElem, 0, 0, videoWidth, videoHeight)
// 導出成blob文件
canvasElem.toBlob(blob => {
const thumbFile = toThumbFile(blob)
}, 'image/png')
})
其中,toThumbFile
的作用是將blob文件轉成file文件
const toThumbFile = blob => new File([blob], 'thumb__img.png')
onloadeddata
噹噹前幀的數據已加載,但沒有足夠的數據來播放指定音頻/視頻的下一幀時,會發生 loadeddata 事件。
當音頻/視頻處於加載過程中時,會依次發生以下事件:
- loadstart
- durationchange
- loadedmetadata
- loadeddata
- progress
- canplay
- canplaythrough