注意事项:
- 服务端必须要有access字段来同意你的跨域请求(https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image)
- 必须服务器环境下调试,本地无法调试(比如 file: 开头的)
- 视频文件所在的域和图片和页面所在域必须相同
示例代码
<html>
<head>
<title>设置视频封面为视频第一帧</title>
<style>
.video{
width:500px;
height:300px;
}
</style>
</head>
<body>
<video src="url" onloadeddata="showFrame(event)" controls="controls" calss="video">
</video>
<script>
function showFrame(event) {
let scale = 0.8,video = event.target,
canvas = document.createElement("canvas"); // 创建一个画布
canvas.width = video.videoWidth * scale;
canvas.height = video.videoHeight * scale;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
try {
video.setAttribute("poster", canvas.toDataURL("image/png"));
}
catch (err) {
console.log("Error: " + err);
}
}
</script>
</body>
</html>