将ECharts图表保存为图片并发送至服务端

1、获取图片的base64值

Function:echartsInstance. getDataURL

(opts: {
    // 导出的格式,可选 png, jpg, svg
    // 注意:png, jpg 只有在 canvas 渲染器的时候可使用,svg 只有在使用 svg 渲染器的时候可用
    type?: string,
    // 导出的图片分辨率比例,默认为 1。
    pixelRatio?: number,
    // 导出的图片背景色,默认使用 option 里的 backgroundColor
    backgroundColor?: string,
    // 忽略组件的列表,例如要忽略 toolbox 就是 [toolbox]
    excludeComponents?: Array.<string>
}) => string

导出图表图片,返回一个 base64 的 URL,可以设置为Image的src。

示例:

let img = new Image();
img.src = myChart.getDataURL({
    pixelRatio: 2,
    backgroundColor: #fff
});

参考:

2、将base64转为blob

function dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    }

dataurl为base64值。

3、将blob内容发送至服务端

this.$axios({
        method: authrequest[0],
        url: authrequest[1],
        headers: header,
        data: imageData, // imageData为第二步转换后的blob,blog.size可获取图片大小,单位为字节
});
经验分享 程序员 微信小程序 职场和发展