Skip to content
On this page

视频第一帧

js
export function getVideoSpecialFrame ({
  videoSrc,
  frameTime = 1,
  width = 640,
  height = 360
}) {
  console.log(videoSrc)
  return new Promise((resolve, reject) => {
    if (!videoSrc) return reject(new Error('视频链接失效,转换失败'))
    let video = document.createElement('video')
    video.setAttribute('crossOrigin', 'anonymous')
    video.src = videoSrc
    // video.width = width;
    // video.height = height;

    video.addEventListener('loadeddata', function () {
      if (frameTime) {
        video.currentTime = frameTime / 1000
      }

      let duration = parseInt(video.duration * 1000)

      setTimeout(() => {
        let { videoWidth, videoHeight } = video
        let canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height

        let scale = videoWidth / width
        let frameWidth = width
        let frameHeight = videoHeight / scale

        let framePositionLeft = (width - frameWidth) / 2
        let framePositionHeight = (height - frameHeight) / 2

        canvas.getContext('2d').drawImage(video, framePositionLeft, framePositionHeight, frameWidth, frameHeight)

        let frameBase64 = canvas.toDataURL('image/jpeg')
        resolve({
          duration: duration,
          video: videoSrc,
          poster: frameBase64
        })
      }, 300)
    })
  })
}


// 使用
getVideoSpecialFrame({
    videoSrc: videoList[0]
}).then(res => {
    setVideoFrame(res.poster || '')
})

粤ICP备2024285819号