vue项目开发有一个需求是可以对视频进行截屏操作.
注意
视频截屏前准备需要在video内添加crossorigin="anonymous"
,不然可能会有跨域问题导致无法截图.
<video class="videoScreenShot" id="videoScreenShot" :controls="true" crossorigin="anonymous" :src="mp4" :autoplay="false"></video>
演示截图
演示地址
实现代码
/**
* @Author: 858834013@qq.com
* @Name: videoScreenShot
* @Date: 2023年2月1日 09:44:35
* @Desc: 视频截图
*/
<template>
<div class="pageMain">
//注意添加crossorigin="anonymous" 避免跨域
<video class="videoScreenShot" id="videoScreenShot" :controls="true" crossorigin="anonymous" :src="mp4" :autoplay="false"></video>
<div class="videoScreenShotBut" @click="screenShot">视频截屏</div>
</div>
</template>
<script>
import mp4 from '@/assets/mp4/mp4.mp4'
export default {
name: "videoScreenShot",
data() {
return {mp4}
},
methods: {
screenShot() {
var player = document.getElementById('videoScreenShot'); //获取video的Dom节点
var canvas = document.createElement("canvas");
var img = document.createElement("img");
canvas.width = player.clientWidth;
canvas.height = player.clientHeight;
canvas.getContext("2d").drawImage(player, 0, 0, canvas.width, canvas.height); //截
var dataURL = canvas.toDataURL("image/png"); //将图片转成base64格式
console.log(dataURL)
this.downFile(dataURL, "截图.png"); //下载截图
},
//下载截图
downFile(data, fileName) {
var save_link = document.createElementNS(
"http://www.w3.org/1999/xhtml",
"a"
); //有效的内部空间URI
save_link.href = data;
save_link.download = fileName;
var event = document.createEvent("MouseEvents");
event.initMouseEvent(
"click",
true,
false,
window,
0,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null
);
save_link.dispatchEvent(event);
},
},
}
</script>
<style lang="scss" scoped>
.videoScreenShot {
width: 600px;
height: 500px;
margin: 0 auto;
}
.videoScreenShotBut {
background: red;
width: 80px;
height: 60px;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: nowrap;
flex-direction: row;
align-content: flex-start;
border-radius: 10px;
color: #fff;
font-size: 16px;
cursor: pointer;
margin-top: 30px;
}
.pageMain {
position: fixed;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: nowrap;
flex-direction: column;
align-content: flex-start;
}
</style>
可能出现的错误
截图时报错Tainted canvases may not be exported.
如果出现了这种错误就是跨域了video内添加crossorigin="anonymous"
即可。