3

我有一个IgniteUI igDataChart,我想将它作为图像保存到磁盘。您不能右键单击图表并保存图像,因为它使用了多个画布。然而,该图表确实有一个导出图像方法,该方法将获取整个图表图像并将其返回到一个 javascript 变量中。

我想通过单击按钮自动将此文件保存到用户的下载文件夹中。如果这是服务器端图像,我可以简单地将用户引导到适当的 url,但事实并非如此。

用户如何通过单击按钮下载此客户端生成的图表 png 图像?我需要一个跨浏览器解决方案。

JSFIDDLE

$(function () {
    $("#exportBtn").click(function(){
       //returns an image DOM element;
       var pngImage = $("#chart").igDataChart("exportImage");
       //now i need to download the image
    });
});
4

2 回答 2

2

该解决方案提供了更好的浏览器支持,并且可以分配给一个按钮。http://jsfiddle.net/koo2hv5t/7/

  1. 检查 blob 支持(您可以为旧浏览器或服务器端回退添加消息)
  2. 等到动画结束
  3. 将图表复制为 dataURL 格式igDataChart
  4. Util.dataURLToBlobhttps://github.com/ebidel/filer.js转换为 blob
  5. saveAs使用https://github.com/eligrey/FileSaver.js将 blob 保存到文件中

    //check support
    try {
        var isFileSaverSupported = !! new Blob;
    } catch (e) {}
    
    setTimeout(function () {
        //add data to url
        function downloadCanvas(link, canv, filename) {
            if (isFileSaverSupported) {
                saveAs(Util.dataURLToBlob(canv.src), filename);
            }
        }
        $("#exportBtn").click(function () {
            downloadCanvas(this, $("#chart").igDataChart("exportImage", 800, 600), 'test.png');
        });
    }, 1000); //wait till animation end
    
于 2015-06-04T21:10:49.313 回答
1

您可以通过以下方式进行:

  1. 等到动画结束
  2. 复制最后一张中的所有画布
  3. 将数据分配给 url(不是按钮)

    setTimeout(function () {
        var c = $("#chart canvas"); //get handle to all canvas
        var ctx = c[c.length - 1].getContext('2d');
        for (i = 0; i < c.length - 1; i++) { //add all canvas to the last one
            ctx.drawImage(c[i], 0, 0);
        }
        for (i = 0; i < c.length - 1; i++) { //remove the duplicates
            c[i].remove();
        }
        //add data to url
        function downloadCanvas(link, canv, filename) {
            link.href = canv.toDataURL();
            link.download = filename;
        }
        $("#dl1").click(function () {
            downloadCanvas(this, c[2], 'test.png');
        });
    
    }, 1000); //wait till animation end
    

http://jsfiddle.net/koo2hv5t/1/

于 2015-06-03T22:49:06.970 回答