Use dom-to-image and file-saver

Steps:

  1. Install [email protected] and [email protected]
NPM install [email protected] [email protected]Copy the code
  1. The introduction of
import domtoimage from 'dom-to-image'
import {saveAs} from 'file-saver'
Copy the code
  1. Save method – The following uses PNG as an example
Domtoimage.toblob (document.getelementById ('tableBox')).then(function (blob) {saveAs(blob, 'file.png '); })Copy the code
Disadvantages: When echarts is saved, Safari is empty

Second, with canvas

let canvas = document.getElementsByTagName('canvas')[0]; let image = canvas.toDataURL({ type:"png", pixelRatio: 2, }); let alink = document.createElement("a"); alink.href = image; Alink. download = 'file name '; alink.click();Copy the code
Advantages: Echarts images work in any browser
Disadvantages: Can only save canvas tag

3, JS save Echarts chart

Implementation approach
  • 1. Obtain the Base64 encoded character of the image by getDataURL();
  • 2. Decode characters and convert them into Blob objects;
  • 3. Create URL objects from Blob objects;
  • 4. Use trigger download operation;
<div class="stacked-chart-box"> <input type="button" value=" export "onclick="saveAsImage()"/> <div id="echartId" class="stacked-chart"></div> </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("echartId"); var myChart = echarts.init(dom); var app = {}; option = null; option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: // 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); } 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 })); 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 }); } </script>Copy the code
Disadvantages: It does not support the download of wechat or Dingding.com’s own browser on the mobile end