获取视频封面
目录
- 实现方式
- 注意事项
- 代码实现
实现方式
通过 video 元素+canvas 元素的方式实现
- 生成 video 和 canvas 元素
- 当 video 元素资源加载完成时,将 video 元素绘制到 canvas 画布上,然后通过 toBlob 或则 toDataURL 获取到对应的封面图片资源
注意事项
video 视频资源为同域或支持跨域
视频链接跨域时有两种解决办法:
- video 元素添加跨域属性,在 video 元素上设置跨域标识。服务器 CORS 配置支持跨域的对应请求头
let videoRef = document.createElement("video");
videoRef.crossOrigin = "anonymous"; // 关键设置
// 确保视频服务器返回以下响应头Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type
- 视频资源上传同域服务器,避免跨域
代码实现
<template><div ref="app"></div>
</template><script lang="ts" setup>import {ref, onMounted} from "vue";
const app = ref()
const initCanvas = async()=> {let videoRef = document.createElement("video");let videoWidth: numberlet videoHeight:numberconst canvasRef = document.createElement("canvas");// 视频资源链接,需要保证该资源支持跨域videoRef.src = "*******"// app.value.appendChild(videoRef);videoRef.muted = truevideoRef.controls = true;videoRef.preload = 'auto';videoRef.addEventListener("loadeddata", () => {videoWidth = videoRef.videoWidthvideoHeight = videoRef.videoHeight// app.value.appendChild(canvasRef);canvasRef.width = videoWidth;canvasRef.height = videoHeight;const ctx = canvasRef.getContext('2d')ctx?.drawImage(videoRef, 0, 0, canvasRef.width, canvasRef.height);// 生成封面图片链接const coverUrl = canvasRef.toDataURL("image/png");})
}onMounted(() => {initCanvas();
})
</script>
- 为了避免loadeddata 事件触发时,视频资源可能并没加载完全,导致 canvas 绘制失败,也可以通过requestAnimationFrame轮询检测视频就绪状态
<template><div ref="app"></div>
</template><script lang="ts" setup>import {ref, onMounted} from "vue";
const app = ref()
const initCanvas = async()=> {let videoRef = document.createElement("video");let videoWidth: numberlet videoHeight:numberconst canvasRef = document.createElement("canvas");// 视频资源链接,需要保证该资源支持跨域videoRef.src = "*****"app.value.appendChild(videoRef);videoRef.muted = truevideoRef.controls = true;videoRef.preload = 'auto';videoRef.addEventListener("loadedmetadata", () => {videoWidth = videoRef.videoWidthvideoHeight = videoRef.videoHeightapp.value.appendChild(canvasRef);canvasRef.width = videoWidth;canvasRef.height = videoHeight;const ctx = canvasRef.getContext('2d')const drawFrame = () => {if(videoRef.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {ctx?.drawImage(videoRef, 0, 0, canvasRef.width, canvasRef.height);// 生成封面图片链接const coverUrl = canvasRef.toDataURL("image/png");}else {requestAnimationFrame(drawFrame)}}drawFrame()})
}onMounted(() => {initCanvas();
})
</script>