将页面某部分截图传入后端
需求详细说明
需要将页面上展示的柱状图(或其他图形或页面上某个提前设定好的区域)进行截图并传给后端,后端将前端传入的图片放入excel中,页面自动下载excel。
实现
//导出图片
handleExport() {
//生成url
const canvas = document.createElement("canvas");//创建画布
let canvasBox = document.getElementById("export-region");//根据id得到要截取的dom
const width = canvasBox.offsetWidth;
const height = canvasBox.offsetHeight;
canvas.width = width;
canvas.height = height;//将画布的设置为dom的宽高
// 生成页面含糊时,能够放大肯定倍数,通过调整canvas的宽高使其清晰度减少
const context = canvas.getContext("2d");
context.scale(1, 1);
const options = {
backgroundColor: null,
canvas: canvas,
useCORS: true
};
html2canvas(canvasBox, options).then(canvas => {
let imgUrl = canvas.toDataURL("image/png");
//将base64文件转换为blob
let blob = dataURLtoBlob(imgUrl); // dataURL-> blob
let file = blobToFile(blob, "截图.png"); // blob -> file
//组织参数
let formData = new FormData();
//将得到的二进制文件加入到formData中
formData.append("PictrueFile", file, "截图.png");
exportPicture(formData).then(res => {
//上面的PictureFile为后端定义的参数名,exportPicture为调用后端接口的函数,需要根据实际情况进行修改
let resBlob = new Blob([res.data], { type: "application/x-xlsx" });
let fileUrl = window.URL.createObjectURL(resBlob);
let link = document.createElement("a");
link.href = fileUrl;
link.setAttribute(
"download",
"数据和图片导出_" + formatDate(+new Date(), "YYYY_MM_DD") + ".xlsx"
);//excel命名‘自定义+当前时间’
link.click();
});
});
},
//所用到的两个函数 dataURLtoBlob blobToFile
/**
* 将base64转换为blob
*/
function dataURLtoBlob(dataUrl){
var 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
});
}
/**
* 将blob转换为file
*/
export const blobToFile = (theBlob, fileName) => {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}