video-cover.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. export const getVideoCover = (data: string | Blob, seekTo: number = 0.0, width?: number, height?: number) : Promise<string> => {
  2. const url = typeof data !== 'string'
  3. ? URL.createObjectURL(data)
  4. : data
  5. return new Promise(function (resolve, reject) {
  6. const video = document.createElement('video')
  7. video.setAttribute('crossOrigin', 'anonymous')// 处理跨域,需要服务器支持跨域
  8. video.setAttribute('src', url)
  9. video.setAttribute('muted', '')
  10. if (width && height) {
  11. video.setAttribute('width', `${width}px`)
  12. video.setAttribute('height', `${height}px`)
  13. video.setAttribute('style', 'object-fit:scale-down')
  14. }
  15. video.load()
  16. video.addEventListener('loadedmetadata', function () {
  17. if (video.duration < seekTo) {
  18. reject(new Error('视频长度不够'));
  19. return;
  20. }
  21. setTimeout(() => video.currentTime = seekTo, 200);
  22. video.addEventListener('seeked', () => {
  23. const canvas = document.createElement('canvas')
  24. if (width && height) {
  25. canvas.width = width
  26. canvas.height = height
  27. } else {
  28. canvas.width = video.videoWidth
  29. canvas.height = video.videoHeight
  30. }
  31. canvas.getContext('2d')!.drawImage(video, 0, 0, width!, height!)
  32. const dataURL = canvas.toDataURL('image/jpeg')
  33. if (typeof data !== 'string') {
  34. video.pause()
  35. URL.revokeObjectURL(url)
  36. }
  37. resolve(dataURL)
  38. })
  39. })
  40. })
  41. }