需求:实现eCharts折线图右上角显示一个下载按钮,点击下载此折线图图片。
实现:
方式一、使用eCharts官方工具 toolbox。
优点:方便,实现简单
option = {
title: {
text: 'Temperature Change'
},
toolbox: { // !!!
show: true,
feature: {
saveAsImage: {} // 导出图片
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value',
axisLabel: {
formatter: '{value} °C'
}
},
series: [
{
name: 'Highest',
type: 'line',
data: [10, 11, 13, 11, 12, 12, 9]
}
]
};
实现效果:
扩展:实现自定义下载按钮样式。
option = {
title: {
text: 'Temperature Change'
},
toolbox: { // !!!
show: true,
feature: {
saveAsImage: {
icon:'path://M 384 448 V 110 h 230 v 310 h 180 l -300 324 l -324 -324 h 180 Z m -170 450 h 600 v 60 H 140 v -60 Z',
iconStyle: {
color:'#000'
}
}
}
},
......
};
实现效果:
更多配置见:官方文档
方式二、自定义按钮节点,设置点击响应事件
优点:
- eCharts自带的下载工具在下载时按钮会消失,下载完成才出现。(下载过程长时才明显)如果要求严格,需要解决这个问题则可以用此方法。
- 设置较复杂的下载按钮样式时比较方便。
(使用vue + typeScript 实现)
<template>
<div>
<Icon type="md-download" size="18" @click="downloadImage" />
<div id="chart"></div>
</div>
</template>
<script lang="ts">
......
public downloadImage(){
const link = document.createElement('a');
link.download = "imageName";
link.style.display = 'none';
link.href = this.chart.getDataURL({
type:'png',
pixelRatio: 1.5,
backgroundColor: '#fff'
}); // 导出图表图片,返回一个 base64 的 URL
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href); //释放URL对象
document.body.removeChild(link);
}
</script>