Save client side image on Click button

I have an IgniteUI igDataChart that I would like to save to disk as an image. You cannot right click on the diagram and save the image because it uses multiple canvases. However, the chart has an image export method that will display the entire chart image and return it to a javascript variable.

I would like to automatically save this file to the user's download folder when a button is clicked. If it was a server side image, I could just direct the user to the appropriate url, but it isn't.

How can a user load this client side with a png image of a chart on a button click? I need a crossbrowser solution.

JSFIDDLE

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

      

+3


source to share


2 answers


This solution offers better browser support and can be assigned to a button. http://jsfiddle.net/koo2hv5t/7/



  • Check blob support (you can add post for older browsers or server side backup)
  • Wait for the animation to end
  • Copy your chart to dataURL format with igDataChart

  • Convert to blob s Util.dataURLToBlob

    from https://github.com/ebidel/filer.js
  • Save blob to file using saveAs

    from https://github.com/eligrey/FileSaver.js

    //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
    
          

+2


source


You can follow the following path:

  • Wait for the animation to end
  • Copy entire canvas to last
  • Assign data to url (not button)

    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/

+1


source







All Articles