echarts柱状图保存为图片并下载
直接附上代码
页面中设置 下载柱状图按钮,带上下载图片名称。
let myChart = echarts.init(this.$refs.barCharts)
// 获取base64位图片
downLoad(title, num) {
if (num === 0) {
let img = new Image();
img.src = this.$refs.barCharts.myChart.getDataURL({
pixelRatio: 2,
backgroundColor: '#001C54'
});
let str = img.src
this.downLoadFile(title + '.png', str)
}
},
// 下载图片
downLoadFile(fileName, content) {
let aLink = document.createElement('a');
let blob = this.base64ToBlob(content); //new Blob([content]);
let event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
//initEvent 事件类型,是否冒泡,是否阻止浏览器的默认行为
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.click()
},
//base64转blob
base64ToBlob(code) {
let parts = code.split(';base64,');
// 文件类型 image/
let contentType = parts[0].split(':')[1];
//parts[1]是base64数据 window.atob用于对base64数据进行解码
let raw = window.atob(parts[1]);
let rawLength = raw.length;
// new Uint8Array(length)创建初始化为0的,包含length个元素的无符号整型数组
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
// charCodeAt()返回指定位置的unicode编码
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}