Search code examples
javascriptnode.jscanvaspluginschart.js

How could I implement chartjs-plugin-datalabels in chartjs-node-canvas?


I am trying to implement ChartJS Datalabels with chartjs-node-canvas in Node. This is my current code

import ChartDataLabels from 'chartjs-plugin-datalabels';
import { ChartJSNodeCanvas } from 'chartjs-node-canvas'

    public async generateChart(width: number, height: number, type: string = 'bar', data, options): Promise<Buffer> {
        const chartCallback = (ChartJS) => {
            ChartJS.plugins.register(ChartDataLabels);
        };
        const chartJSNodeCanvas: ChartJSNodeCanvas = new ChartJSNodeCanvas({ width, height, chartCallback})
        const configuration: any =
        {
            type: type,
            data: data,
            options: options
        };
        const image = await chartJSNodeCanvas.renderToBuffer(configuration);
        return image
    }

I have tried in various ways although I have not been able to find an optimal solution

// Option 1
const chartJSNodeCanvas = new ChartJSNodeCanvas({ width, height, plugins: {
    requireLegacy: ['chartjs-plugin-datalabels']
} });

// Option 2
const chartCallback = (ChartJS) => {
    ChartJS.plugins.register(ChartDataLabels);
};
const chartJSNodeCanvas = new ChartJSNodeCanvas({ width, height, chartCallback });

But I have not been able to generate the PDF with Datalabels although I have generated it without using the plugin. The error is

System.Private.CoreLib: Exception while executing function: Functions.test1. System.Private.CoreLib: Result: Failure
Exception: TypeError: Cannot read property 'register' of undefined
Stack: TypeError: Cannot read property 'register' of undefined
    at ChartJSNodeCanvas.initialize (C:\project\node_modules\chartjs-node-canvas\dist\new.js:172:33)
    at new ChartJSNodeCanvas (C:\project\node_modules\chartjs-node-canvas\dist\new.js:27:30)
    at ReportLpi.<anonymous> (C:\project\dist\src\services\report_lpi.js:1121:39)
    at Generator.next (<anonymous>)

The variable type, data, options are the same of the next code.

var ctx = document.getElementById("myChart");
var chart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: ["a", "b", "c", "d", "e", "f"],
    datasets: [
      {
        type: "bar",
        backgroundColor: "blue",
        borderColor: "blue",
        borderWidth: 1,
        label: "promedio",
        order: 1,
        data: [60, 49, 72, 90, 100, 60],
                    datalabels: {
                        align: 'end',
                        anchor: 'end'
                    }
      },
      {
        type: "bar",
        backgroundColor: "orange",
        borderColor: "orange",
        borderWidth: 1,
        label: "promedio",
        order: 1,
        data: [40, 5, 20, 30, 10, 6],
                    datalabels: {
                        align: 'end',
                        anchor: 'end'
                    }
      },
      {
        type: "line",
        label: "casos",
        data: [25, 13, 30, 35, 25, 40],
        lineTension: 0,
        backgroundColor: "red",
        borderColor: "red",
        order: 0,
        fill: false,
                    datalabels: {
                        align: 'end',
                        anchor: 'end'
                    }
      }
    ]
  },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        },
        legend: {
          display: false
        },
        plugins: {
      datalabels: {
                    backgroundColor: function(context) {
                        return context.dataset.backgroundColor;
                    },
                    borderRadius: 4,
                    color: 'white',
                    font: {
                        weight: 'bold'
                    },
                }
    }
      }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>

<body>
  <canvas id="myChart" width="400" height="200"></canvas>
</body>


Solution

  • Apparently version 3.X.X has several bugs to add a plugin, I finished solving by following this Issues

    import { ChartJSNodeCanvas } from 'chartjs-node-canvas';
    
    const canvas = new ChartJSNodeCanvas({
      width: 700,
      height: 400,
      chartCallback: (ChartJS) => {
        /** Add plugins here **/
        ChartJS.register(require('chartjs-plugin-datalabels'))
      }
    });