echarts图标保存成图片并下载

标签(空格分隔): js


用echarts下载图片的代码

toolbox: {
            show: true,
            feature: {
                saveAsImage: {
                show:true,
                excludeComponents :['toolbox'],
                pixelRatio: 1 
                }
            }
        },

这样写发现报错
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
就意思是画布已经被污染,不能够下载,因为我们用了graphic去展示图片

于是就想办法自己触发下载
1, 显示图片的地方转换为base64

 //默认是加号图片
                    {
                        type: 'image',
                        position: myChart.convertToPixel('grid', item.value),
                        style: {
                            image: picPath,
                            x: 10, ,
                            y: -10,
                            width: 100,
                            height: 100,
                        },
                        z: 10
                    },

2,先让页面显示的时候正常加载,然后转为base64之后再去加载

//图片转换为base64编码
function imageToBase64(imgPath, index) {
    var img = new Image();
    img.crossOrigin = 'anonymous';
    img.src = imgPath;
    var dataURL;
    img.onload = function () {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
        dataURL = canvas.toDataURL('image/png');
        dataArr[index].param.nodePicBase64 = dataURL;
    };
}
然后再去遍历每一个item,dataArr是ehcrts数据
   for (var i = 0; i < dataArr.length; i++) {
        var picPath = dataArr[i].param.nodePicPath;
        if (picPath !== "" && picPath !== defaultPic) {
            imageToBase64(picPath, i);
        }
    }

3,触发按钮

$("#downLoadId").click(function () { //触发按钮
    var path = myChart.getDataURL({
        backgroundColor: '#fff',
    });
   downloadImage(path, "echarts");
});
/**
 * 
 * @param {*} path src路径 imgName 图片名称
 */
function downloadImage(path, imgName) {
    var _OBJECT_URL;
    var request = new XMLHttpRequest();
    request.addEventListener('readystatechange', function (e) {
        if (request.readyState == 4) {
            _OBJECT_URL = URL.createObjectURL(request.response);
            var $a = $("").attr("href", _OBJECT_URL).attr("download", imgName);
            $a[0].click();
        }
    });
    request.responseType = 'blob';
    request.open('get', path);
    request.send();
}

你可能感兴趣的:(echarts图标保存成图片并下载)