vue html2canvas截屏
安装
npm install --save html2canvas
引入
import html2canvas from "html2canvas";
注意如果遇到在截图过程中没有图片,可以加上“crossorigin”试试
具体代码
<template>
<div id="divId">
<video crossorigin="anonymous" :src="video" />
<img crossorigin="anonymous" style="height: 80px;width: 80px;" :src="photo" />
</div>
</template>
<script>
import html2canvas from "html2canvas";
export default {
name: "demo",
data() {
return {
video: "",
photo: ""
};
},
methods: {
onCapture() {
// 获取要截图的区域
html2canvas(document.getElementById("divId")).then((canvas) => {
let url = canvas.toDataURL("image/png");
// 将图片转换为base64格式
this.getBase64(url);
});
},
// 将图片转换为base64格式, 防止图片出现跨域的问题
async getBase64(imgUrl) {
var _this = this;
// 将图片转为base64格式
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open("get", imgUrl, true);
// 至关重要
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status === 200) {
//得到一个blob对象
var blob = this.response;
console.log("blob", blob);
// 至关重要
let oFileReader = new FileReader();
oFileReader.onloadend = function(e) {
// 下载图片
let aLink = document.createElement("a");
aLink.style.display = "none";
aLink.href = e.target.result;
//存入页面指定位置
aLink.download = "截图.png";
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
};
oFileReader.readAsDataURL(blob);
}
};
xhr.send();
},
// 特别注意!!! 在截图视频监控或者地图map时,截图出来的图像会变成黑色,不会显示图像,需要在初始化地图或者视频监控时添加下面的代码即可,
getVideoData(url, id) {
this.playerDestroy();
// 调用前先暂停销毁视频
this.player = new EZUIKit.EZUIKitPlayer({
id: "yingshi", // 视频容器ID
accessToken: this.token,
url,
audio: 0, // 是否默认开启声音 0 - 关闭 1 - 开启
autoplay: true,
template: "security",
width: this.$refs.fullscreen.clientWidth,
height: 800
});
// 解决html2canvas截图空白问题
HTMLCanvasElement.prototype.getContext = (function(origFn) {
return function(type, attributes) {
if (type === "webgl") {
attributes = Object.assign({}, attributes, {
preserveDrawingBuffer: true
});
}
return origFn.call(this, type, attributes);
};
})(HTMLCanvasElement.prototype.getContext);
}
}
};
</script>