JS实现Echarts的图表保存为图片功能
2020-7-31 dingshangchao JavaScript
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。
实现思路:
通过getDataURL()获取图片的base64编码字符;
字符解码,并转换成Blob对象;
通过Blob对象创建URL对象;
利用<a>触发下载操作;
具体代码:
<!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>
« css常用工具类
|
网页打开微信并跳转到指定页面»