js实现ECharts图表的下载
方法一:
ECharts自带的方法,在toolbox配置项,feature里面有一个saveAsImage方法:
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>吾学网 – 5xue.cc – js实现ECharts图表的下载</title> <!--引入echarts.js --> <script type="text/javascript" src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script> </head> <body> <!-- 为ECharts准备一个容器 --> <div id="container" style="width: 600px;height:400px;"></div> <script type="text/javascript"> //初始化echarts实例 var myChart = echarts.init(document.getElementById('container')); //配置图表项和数据 var option = { title: { text: '第一个 ECharts 实例' }, tooltip: {}, legend: { data:['销量'] }, xAxis: { data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"] }, yAxis: {}, toolbox: { show: true, feature: {saveAsImage: {}} }, series: [{ name: '销量', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }; //绘制图表 myChart.setOption(option, true); </script> </body> </html> |
方法二:
Echarts提供一个接口getDataURL,通过它可以导出图表图片,返回一个 base64 的 URL。实现思路:
- 通过getDataURL()获取图片的base64编码字符;
- 字符解码,并转换成Blob对象;
- 通过Blob对象创建URL对象;
- 利用触发下载操作;
代码如下:
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>吾学网 – 5xue.cc – js实现ECharts图表的下载</title> <!--引入echarts.js --> <script type="text/javascript" src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script> </head> <body> <!-- 为ECharts准备一个容器 --> <div id="container" style="width: 600px;height:400px;"></div> <input type="button" value="下载图表" onclick="saveImage()" /> <script type="text/javascript"> //初始化echarts实例 var myChart = echarts.init(document.getElementById('container')); //配置图表项和数据 var option = { title: { text: '第一个 ECharts 实例' }, tooltip: {}, legend: { data:['销量'] }, xAxis: { data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"] }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }; //绘制图表 myChart.setOption(option, true); 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(); let aLink = document.createElement('a'); let blob = this.base64ToBlob(content); let evt = document.createEvent("HTMLEvents"); evt.initEvent("click", true, true); aLink.download = "ECharts报表.png"; aLink.href = URL.createObjectURL(blob); aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window})); } </script> </body> </html> |