需求是将页面上存在的图表转换成图片的方式传给后端,然后后端生成word文档。图表使用的是echarts,如果只单独截图表部分的话可以使用echarts自带的api。但是!内容还包含其他部分。于是就使用了html2canvas。
1:安装
npm i html2canvas --save
2:引入
import html2canvas from ‘html2canvas’
3: 使用
//xxx代表你要截取的dom元素
html2canvas(xxx, {
useCORS: true, //跨域
scale: 0.5 //根据需要配置缩放比例
}).then(canvas => {
//生成base64
let dataUrl = canvas.toDataURL('image/png');
//后端要求传file对象
//先转换成blob,再转成file
let blob = this.dataURLtoBlob(dataUrl);
let file = this.blobToFile(blob, imageName+ '.png');
})
//转成blob
dataURLtoBlob(dataurl) {
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
});
},
//转成file
blobToFile(theBlob, fileName) {
let file = new File([theBlob], fileName, {
type: 'image/png',
lastModified: Date.now()
});
return file;
},