最近碰到一个需求,要求获取在线视频文件的第一帧画面作为视频的封面图片,项目中使用的是 xgplayer 播放器,封面 poster 要求传封面的 url。
思路:用 canvas 绘出画面 - 转成 base64 - base64 转成 File - 获取 File 的本地预览地址
获取 base64 格式的封面
这里 video 元素需添加 autoplay 属性,否则在一些浏览器上获取到的画面是黑的。还有就是先把 video 元素添加到 body 标签再移除,有时候会碰到视频在后台播放,用户根本没有可操作的地方。
export const getVideoBase64 = (url: string) =>
new Promise(function (resolve) {
let dataURL = ''
let video = document.createElement('video')
video.setAttribute('crossOrigin', 'anonymous') //处理跨域
video.setAttribute('src', url)
video.setAttribute('width', 880 +