1,下载html2canvas插件
npm install --save html2canvas
2,引入html2canvas
import html2canvas from 'html2canvas';
1,图片的格式转换
public dataURLToBlob(dataurl: any): any {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
2,对dom生成图片
public saveImage(imgText: string): any {
const canvasID: any = document.getElementById('map-container');
// let that = this;
const a = document.createElement('a');
const opts = {
tainttest: true, // 检测每张图片都已经加载完成
useCORS: true, // 跨域处理,可以加载网络图片
logging: true, // 日志开关
};
html2canvas(canvasID, opts).then((canvas) => {
const dom = document.body.appendChild(canvas);
dom.style.display = 'none';
a.style.display = 'none';
document.body.removeChild(dom);
const blob = this.dataURLToBlob(dom.toDataURL('image/png'));
a.setAttribute('href', URL.createObjectURL(blob));
// 这块是保存图片操作 可以设置保存的图片的信息
a.setAttribute('download', imgText + '.png');
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(blob);
document.body.removeChild(a);
});
}
注意:
对于处理地图的卫星地图图层还有一些跨域图片来说一定要写useCORS: true,useCORS这个属性主要是处理网络图片
网友评论