9

Why can't my code save my chart as an image? Do I have a mistake somewhere? Although I followed the source (found online), I still can't solve my problem.

I can show the chart but only the problem is cannot save as an image.

<script type="text/javascript" src="js/jsapi.js"></script>
    <script type="text/javascript">
    function saveAsImg(chartContainer, pngfilename) {
    var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
    var svg = chartArea.innerHTML;
    var doc = chartContainer.ownerDocument;
    var canvas = doc.createElement('canvas');
    canvas.setAttribute('width', chartArea.offsetWidth);
    canvas.setAttribute('height', chartArea.offsetHeight);
    canvas.setAttribute(
    'style',
    'position: absolute; ' +
    'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
    'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
    doc.body.appendChild(canvas);
     canvg(canvas, svg);
    var data = canvas.toDataURL("image/png");
    canvas.parentNode.removeChild(canvas);
    data = data.substr(data.indexOf(',') + 1).toString();

    var dataInput = document.createElement("input") ;
    dataInput.setAttribute("name", 'imgdata') ;
    dataInput.setAttribute("value", data);

    var nameInput = document.createElement("input") ;
    nameInput.setAttribute("name", 'name') ;
    nameInput.setAttribute("value", pngfilename + '.png');

    var myForm = document.createElement("form");
    myForm.method = 'post';
    myForm.action = 'saveme.php';
    myForm.appendChild(dataInput);
    myForm.appendChild(nameInput);

    document.body.appendChild(myForm) ;
    myForm.submit() ;
    document.body.removeChild(myForm) ;

}


</script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages: ['corechart']});
    </script>

    <script type="text/javascript">


      function drawVisualizationDaily() {
        // Create and populate the data table.
        Price1=document.getElementById('Price1').value;
        Price2=document.getElementById('Price2').value;
        Price3=document.getElementById('Price3').value;
        Price4=document.getElementById('Price4').value;
        Price5=document.getElementById('Price5').value;
        Price6=document.getElementById('Price6').value;
        Price7=document.getElementById('Price7').value;
        var data = google.visualization.arrayToDataTable([
          ['Daily', 'Sales'],
          ['Mon', parseInt(Price1) ],
          ['Tue', parseInt(Price2) ],
          ['Wed', parseInt(Price3) ],
          ['Thu', parseInt(Price4) ],
          ['Fri', parseInt(Price5) ],
          ['Sat', parseInt(Price6) ],
          ['Sun', parseInt(Price7) ]
        ]);

        // Create and draw the visualization.
        new google.visualization.ColumnChart(document.getElementById('visualization')).
            draw(data,
                 {title:"Daily Sales",
                  width:500, height:400,
                  hAxis: {title: "Daily"}}
            );
       }  


      google.setOnLoadCallback(drawVisualizationDaily);
    </script>

    <div id="visualization" style="width: 600px; height: 400px;"></div>
    <script>
    <a href='#' onClick="saveAsImg(document.getElementById('visualization'), 'test');">Test</a>
</script>
Melanie Palen
  • 2,645
  • 6
  • 31
  • 50
user3438249
  • 113
  • 1
  • 1
  • 3

1 Answers1

19

That method is no longer necessary to get an image of the chart. You can call the chart's getImageURI method instead to get a URL string for generating the image:

var chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'ready', function () {
    var imgUri = chart.getImageURI();
    // do something with the image URI, like:
    window.open(imgUri);
});
chart.draw(data, {
    title:"Daily Sales",
    width:500,
    height:400,
    hAxis: {title: "Daily"}
});

If you open the image URI, you can right-click the image to save it.

asgallant
  • 26,060
  • 6
  • 72
  • 87
  • 3
    Here's an example that puts the chart image into an `` tag on the page. You can right-click the image and save it. http://jsfiddle.net/asgallant/R8A8P/ – asgallant Mar 20 '14 at 16:46
  • still got 1 question to ask you..if i want implement a link,let user click to download the chart image, then what should i do with the – user3438249 Mar 21 '14 at 01:46
  • 3
    You need to change the mime type of the URI to "application/octet-stream", and call `window.open`, passing in the URI, which should trigger a download ([example](http://jsfiddle.net/asgallant/R8A8P/1/)). You cannot specify the file name when you do this. If you need to rename the file, you will have to send the URI to your server and have the server create the file (similar to how the code in your question works). – asgallant Mar 21 '14 at 02:20
  • Ok..but you give the example since like got error..cannot get the chart image – user3438249 Mar 21 '14 at 14:51
  • You got an error using my example? What browser did you use that generated the error? – asgallant Mar 21 '14 at 15:28
  • it cannot download the chart image, but when i click the example then it will open jsfiddle page and open a blank page with nothing – user3438249 Mar 21 '14 at 16:10
  • What browser are you using? – asgallant Mar 21 '14 at 17:36
  • can you provide me full code with downloading image? – user3438249 Mar 22 '14 at 16:37
  • If I recall correctly, this code will not work in Internet Explorer at all (IE 8 does not use SVG, so it just fails; IE 9+ doesn't seem to like triggering a download on the image stream URI). I made an improved version of the code that allows you to rename the file (in Chrome, Firefox, and Opera any way): http://jsfiddle.net/asgallant/R8A8P/2/. If you want to be able to download the chart as an image in IE 9+, I think your only course of action is to create an `` tag and have your users right-click on it to save the image (like the first example: http://jsfiddle.net/asgallant/R8A8P/). – asgallant Mar 24 '14 at 15:03
  • What I did was simply create a link with an id attribute and a dummy href attribute, and then the javascript stuffed the correct URI into the href (from getImageURI). You can view the source and look for "imgUri" here: http://www.sealevel.info/co2.html (The "dummy" href attribute is actually the URL of a stub page which says, "Sorry, you need to have JavaScript enabled in your web browser to use this feature.") – Dave Burton Mar 31 '16 at 22:02