vue3 video 播放标签,截图并下载图片到本地
效果图1
效果图2
1、html代码 部分
<video autoplay controls loopobject-fit:cover crossOrigin="anonymous" id="videoElement"
src="https://video19.ifeng.com/video09/2022/11/10/p6996366852502851668-102-150552.mp4?reqtype=tsl"></video>
<button @click="selaction ">截取</button>
ps( crossOrigin="anonymous" 这个属性是报错 SecurityError: Failed to execute toDataURL on HTMLCanvasElement : Tainted canvases may not be exported.) 设置的
js代码部分
// 截图转换---------------------------下载------------------------
const dataURLtoBlob = (dataurl: any) => {
let arr = dataurl.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
const downloadFile = (url: any, name = "What's the fuvk") => {
let a = document.createElement("a");
a.setAttribute("href", url);
a.setAttribute("download", name);
a.setAttribute("target", "_blank");
let clickEvent = document.createEvent("MouseEvents");
clickEvent.initEvent("click", true, true);
a.dispatchEvent(clickEvent);
};
// 两个参数,第一个是base64地址 第二个是下载后的图片名字
const downloadFileByBase64 = (base64: any, name: any) => {
let myBlob = dataURLtoBlob(base64);
let myUrl = URL.createObjectURL(myBlob);
downloadFile(myUrl, name);
};
const numbsel = ref();
const imgUrl = ref();
// 点击截图按钮
const selaction = () => {
let video = document.getElementsByTagName("video")[0]; // 获取video节点
let canvas = document.createElement("canvas"); // 创建canvas节点
let w = video?.clientWidth;
let h = video?.clientHeight;
canvas.width = w;
canvas.height = h; // 设置宽高
const ctx = canvas.getContext("2d");
ctx?.drawImage(video, 0, 0, w, h); // video写入到canvas clientHeight
imgUrl.value = canvas.toDataURL("image/png"); // 生成截图地
downloadFileByBase64(imgUrl.value, "滴滴答答");
};
感谢这位博主的文章,web端video截图和录屏功能的实现_video 截图_倾尽天下yhs的博客-CSDN博客
录屏这些可以去参考这位博主