<!DOCTYPE html>
<html style="height: 100%">
<head>
<meta charset="utf-8">
<title>JS实现Echarts的图表保存为图片功能</title>
<script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script>
</head>
<body style="height: 100%; margin: 0">
<button onclick="saveImage()">导出图片</button>
<div id="container" style="height: 100%"></div>
</body>
<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'
},
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 saveImage() {
let content = myChart.getDataURL({backgroundColor:"#fff"});
let aLink = document.createElement('a');
let blob = this.base64ToBlob(content);
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true);
aLink.download =new Date() + ".png";
aLink.href = URL.createObjectURL(blob);
aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
}
</script>
</html>
<!-- 使用vue实现方法直接把base64ToBlob,saveImage写在methods里面 -->
echarts自定义名称通过当前时间下载图片
于 2022-08-24 16:10:12 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)