Search code examples
javascriptangulartypescriptchart.js

Export chart.js as image


My chart generation function looks like this:

createChart(db_data: string[], count: number[]) {
    const chartOptions = {
      type: 'horizontalBar',
      data: {
        labels: db_data,
        datasets: [
          {
            label: 'Chart',
            data: count,
            borderColor: '#99f0d1',
            backgroundColor: '#60b3a1',
            borderWidth: 0.1,
          },
          
        ],
      },
      onAnimationComplete: function()
      {
          this.showTooltip(this.datasets[0].data, true);
      },
      options: {
...


    this.chartElement = document.getElementById('canvas');
    this.chart = new Chart(this.chartElement, chartOptions);

I want to export this as image(png) but the trick is, that i want to modify the background and bar's colors. My export function is works well, but i cant set the modified background attributes.

exportChart() {
  const currentDate = new Date().toISOString().slice(0, 10);
  
  
  const canvas = this.chart.canvas;

  console.log(canvas);
  canvas.style.backgroundColor = 'blue';


  const chartDataURL = this.chart.toBase64Image();

  
  canvas.style.backgroundColor = 'blue'; 

  const link = document.createElement('a');
  link.href = chartDataURL;
  link.download = `statistic_${currentDate}.png`;
  link.click();
}

I tried to modified the chart generation (with ctx)


Solution

  • As described in the documentation if you want to download the chart with a background color you will need to use a custom plugin for this:

    var options = {
      type: 'line',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            borderColor: 'pink'
          },
          {
            label: '# of Points',
            data: [7, 11, 5, 8, 3, 7],
            borderColor: 'orange'
          }
        ]
      },
      options: {
        plugins: {
          customCanvasBackgroundColor: {
            color: 'pink'
          }
        }
      },
      plugins: [{
        id: 'customCanvasBackgroundColor',
        beforeDraw: (chart, args, options) => {
          const {
            ctx
          } = chart;
          ctx.save();
          ctx.globalCompositeOperation = 'destination-over';
          ctx.fillStyle = options.color || '#99ffff';
          ctx.fillRect(0, 0, chart.width, chart.height);
          ctx.restore();
        }
      }]
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js"></script>
    </body>