Chartsjs export PNG automatically

0

I need to export a Chart and Chartjs (version 2.7) to PNG I got in:

link

The only problem I need to push the button.

Would anyone know what to modify in javascript?

In the end I'm going to generate a report with FPDF in PHP, so I need PNG.

    
asked by anonymous 24.11.2017 / 12:46

1 answer

1

Just call the function: downloadImage(); , so when the page loads it executes the function without the click.

I placed the function in your JSFiddle, and had it re-run the code and downloaded the image without the click.

var chart_variable = new Chart(ctx, {
   type: 'line',
   data: {
      labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
      datasets: [{
         label: 'My First Dataset',
         data: [3, 1, 4, 2, 5],
         backgroundColor: 'rgba(0, 119, 290, 0.2)',
         borderColor: 'rgba(0, 119, 290, 0.6)'
      }]
   },
   options: {
      title: {
         display: true,
         text: 'Chart Title'
      },
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 1
            }
         }]
      }
   }
});

function downloadImage() {
   /* set new title */
   chart_variable.options.title.text = 'New Chart Title';
   chart_variable.update({
      duration: 0
   });
   // or, use
   // chart_variable.update(0);

   /* save as image */
   var link = document.createElement('a');
   link.href = chart_variable.toBase64Image();
   link.download = 'myImage.png';
   link.click();

   /* rollback to old title */
   chart_variable.options.title.text = 'Chart Title';
   chart_variable.update({
      duration: 0
   });
   // or, use
   // chart_variable.update(0);
}

//executa a função ao abrir a página.
downloadImage();
    
24.11.2017 / 14:35