echarts custom icon calls the download/save image function of echarts

 Scenes:

The chart needs to be equipped with a function to save pictures. Of course, echarts itself comes with this function, but due to style issues, it is necessary to draw a download icon outside the chart itself and implement the function of saving pictures.

Since I haven't found out how to call this function directly from the outside, I sealed it myself based on the implementation of the source code and recorded it here.

The picture on the left is the download that comes with echats. You can set its left, center, right, etc. positions, but it is not suitable for my UI.

The picture on the right is the style after I encapsulated it. 

   

This is the configuration place for saving images on the official website  Documentation - Apache ECharts

Code: 

/**
 * echarts图表-保存图片
 * @param {*} myChart 图表
 */
export function downloadEchartsImg() {
  var myChart = echarts.getInstanceByDom(this.$refs.myChart);
  var url = myChart.getConnectedDataURL({
    pixelRatio: 5, //导出的图片分辨率比率,默认是1
    backgroundColor: '#fff', //图表背景色
    excludeComponents: [ //保存图表时忽略的工具组件,默认忽略工具栏
      'toolbox'
    ],
    type: 'png' //图片类型支持png和jpeg
  });
  var $a = document.createElement('a');
  var type = 'png';
  $a.download = myChart.getOption().title[0].text + '.' + type;
  $a.target = '_blank';
  $a.href = url;
  // Chrome and Firefox
  if (typeof MouseEvent === 'function') {
    var evt = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: false
    });
    $a.dispatchEvent(evt);
  }
  // IE
  else {
    var html = ''
      + '<body style="margin:0;">'
      + '<img src="' + url + '" style="max-width:100%;" title="' + myChart.getOption().title[0].text + '" />'
      + '</body>';
    var tab = window.open();
    tab.document.write(html);
  }
}

Original source:https://www.cnblogs.com/chunyangji/p/5818322.html

If you find a better method, thank you for providing it!​ 

Guess you like

Origin blog.csdn.net/qq_58340302/article/details/130904833