Chartjs-Save graph as image after click link full script

4👍

in that case you don’t need to upload as an image.
you could put the result of the call to toDataUrl function in the value of a hidden field and send it in a form (with an iframe as target) or by an ajax call

use the following options in the chart

//new options var
var options = {
    bezierCurve : false,
    //animation: false
    onAnimationComplete: done
};

//your code with a little modification
$(document).ready( 
    function () {
        var ctx = document.getElementById("myChart").getContext("2d");

        //use the previously defined "options" here!!!
        var myNewChart = new Chart(ctx).Pie(data, options);
    }
);

//callback function, called when the pie ends his animation
function done(){
    //this part of your code was moved here to avoid that store an empty image
    document.getElementById("canvas_link").src = document.getElementById("myChart").toDataURL();

    var postdata={
      file: document.getElementById("myChart").toDataURL()
    }
    $.post( "store.php", postdata)
      .done(function( ret ) {
        console.log( "Data status: Loaded successfully ");
      })
      .fail(function( ret ) {
        console.log( "Data status: error ");
      })
    ;
}

Reference: http://api.jquery.com/jquery.post/

in php you can handle the content in this way

// file: store.php

// Interpret data uri
$uriPhp = 'data://' . substr($file, 5);
// Get content
$binary = file_get_contents($uriPhp);

$file = 'uploads/charts/'. time() .'.png';

// Save image
file_put_contents($file, $binary);

Reference: https://github.com/nnnick/Chart.js/issues/99#issuecomment-75359927

-1👍

As per the documentation, you can print or save graph by API calls;

Example

var chart = new CanvasJS.Chart("chartContainer", {
    theme: "theme2",
    title:{
        text: "Print Chart using print() method"              
    },
    data: [              
    {
        type: "column",
        dataPoints: [
            { label: "apple",  y: 10  },
            { label: "orange", y: 15  },
            { label: "banana", y: 25  },
            { label: "mango",  y: 30  },
            { label: "grape",  y: 28  }
        ]
    }
    ]
});

chart.render();
document.getElementById("printChart").addEventListener("click",function(){
    chart.print();
    //chart.exportChart({format: "jpg"});
});     

Leave a comment