需求分析
实际项目开发过程中经常会有图表展示功能,同时为了满足用户需要,会附带着图表导出功能,主要形式就是保存为图片。在Echarts中本身就提供这种配置项,使用起来简单方便。但是,需求分析师要求必须有一个图表导出功能按钮,以便与整体样式风格相搭,对于这种要求。。。
开发准备
通过查看Echarts网站,可以很快找到其自带的toolbox配置项,在feature里面有一个saveAsImage,效果大概是下图:
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
toolbox: {
show: true,
feature: {
saveAsImage: {}
}
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line'
}]
};
另外Echarts提供一个接口getDataURL,通过它可以导出图表图片,返回一个 base64 的 URL
具体代码:
DOCTYPE html>
<html style="height: 100%">
<head>
<meta charset="utf-8">
<title>JS实现Echarts的图表保存为图片功能title>
head>
<body style="height: 100%; margin: 0">
<input type="button" value="导出" onclick="saveAsImage()"/>
<div id="container" style="height: 100%">div>
<script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/echarts.min.js">script>
<script type="text/javascript">
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};
option = null;
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
// toolbox: {
// show: true,
// feature: {
// saveAsImage: {}
// }
// },
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line'
}]
};
if (option && typeof option === "object") {
myChart.setOption(option, true);
}
console.log(myChart.getDataURL());
//base64转blob
function base64ToBlob(code) {
let parts = code.split(';base64,');
let contentType = parts[0].split(':')[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
function saveAsImage() {
let content = myChart.getDataURL();
let aLink = document.createElement('a');
let blob = this.base64ToBlob(content);
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true);
aLink.download = "line.png";
aLink.href = URL.createObjectURL(blob);
aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
}
script>
body>
html>