无后台将echarts图表生成图片下载

无后台将echarts图表生成图片下载

需求分析

如题
本实例基于vue+elementui

生成图片

思路

通过canvas将echart图表生成base64格式图片并放入canvas
导出canvas下载

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const container = document.createElement('canvas')
const toCanvasELs = this.$refs.container.map(component => component.$el)
const len = toCanvasELs.length
container.width = 2526
container.height = 1785 * len
const ctx = container.getContext('2d')
toCanvasELs.forEach((dom, index) => {
html2canvas(dom).then(canvas => {
const img = new Image()
img.src = canvas.toDataURL('image/png', 1.0)
img.onload = _ => {
img.height = 1785
ctx.drawImage(img, 0, img.height * index, 2526, img.height)
// downloadbase64 function定义在下面
if(index === len - 1) this.downloadbase64(container.toDataURL('image/png', 1.0))
}
})
})

特殊处理

假设子组件属性中存在是否导出的isShow可控属性
在$ref.container中可接收isShow
1
2
3
4
5
6
7
8
9
// const toCanvasELs = this.$refs.container.map(component => component.$el)
// 修改为
const toCanvasELs = [];
// 图表是否显示
for(var i=0;i<this.$refs.container.length;i++){
if(this.$refs.container[i].isShow){
toCanvasELs.push(this.$refs.container[i].$el)
}
}

Other

container中的宽高可以按需设置
不建议过大 在浏览器中性能消耗过大

下载图片

问题

因为生成的图片是data:image/png;base64,xxxxx格式
无法直接输出浏览器下载

解决

使用application / octet-stream替换image/png
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
downloadbase64:function(img){
// atob to base64_decode the data-URI
var image_data = atob(img.split(',')[1]);
// Use typed arrays to convert the binary data to a Blob
var arraybuffer = new ArrayBuffer(image_data.length);
var view = new Uint8Array(arraybuffer);
for (var i=0; i<image_data.length; i++) {
view[i] = image_data.charCodeAt(i) & 0xff;
}
try {
// This is the recommended method:
var blob = new Blob([arraybuffer], {type: 'application/octet-stream'});
} catch (e) {
// The BlobBuilder API has been deprecated in favour of Blob, but older
// browsers don't know about the Blob constructor
// IE10 also supports BlobBuilder, but since the `Blob` constructor
// also works, there's no need to add `MSBlobBuilder`.
var bb = new (window.WebKitBlobBuilder || window.MozBlobBuilder);
bb.append(arraybuffer);
var blob = bb.getBlob('application/octet-stream'); // <-- Here's the Blob
}

// Use the URL object to create a temporary URL
var url = (window.webkitURL || window.URL).createObjectURL(blob);
location.href = url; // <-- Download!
}
# Html, JS

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×