<template>
<section>
<section id="myEcharts"></section>
<a-button @click="onClick">点击</a-button>
</section>
</template>
<script>
import echarts from 'echarts';
import { exportImg } from '@/utils/exportEchartsByExternal';
require('echarts/lib/chart/line');
export default {
name: 'Echarts',
mounted() {
this.draw();
},
methods: {
draw() {
const echartsDom = document.getElementById('myEcharts');
const echart = echarts.init(echartsDom);
echart.setOption({
toolbox: [
{
show: true,
orient: 'vertical',
right: 20,
top: 20,
feature: {
saveAsImage: {
show: true,
icon: 'M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0',
connectedBackgroundColor: '#fff',
title: '保存图片',
type: 'png',
pixelRatio: 1,
},
},
},
],
tooltip: {
trigger: 'axis',
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
},
yAxis: {
type: 'value',
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line',
},
],
});
window.addEventListener('resize', () => {
echart.resize();
});
},
onClick() {
exportImg('myEcharts');
},
},
};
</script>
<style>
#myEcharts {
position: relative;
width: 4rem;
height: 2rem;
margin: 0 auto;
}
</style>
import echarts from 'echarts';
export const convertBase64UrlToBlob = (base64) => {
const parts = base64.dataURL.split(';base64,');
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; i++) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
};
export const exportImg = (id, name) => {
const myChart = echarts.getInstanceByDom(
document.getElementById(id)
);
const url = myChart.getConnectedDataURL({
pixelRatio: 1,
backgroundColor: '#fff', // 图表背景色
excludeComponents: [
'toolbox', // 保存图表时忽略的工具组件,默认忽略工具栏
],
type: 'png', // 图片类型支持png和jpeg
});
const a = document.createElement('a');
a.download = `${name}.png`;
a.target = '_blank';
a.href = url;
// Chrome and Firefox
if (typeof MouseEvent === 'function') {
const evt = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: false,
});
a.dispatchEvent(evt);
} else {
// IE
const base64 = {
dataURL: url,
type: 'png',
ext: 'png',
};
const blob = convertBase64UrlToBlob(base64);
// 下载
window.navigator.msSaveBlob(
blob,
`${name}.png`
);
}
};