[Chartjs]-TypeError: CanvasRenderService is not a constructor

3👍

They have renamed their service from CanvasRenderSerice in version 2.x.x to ChartJSNodeCanvas in version 3.x.x.

So you might be using version 3.x.x. Either downgrade your chartjs-node-canvas version 2.x.x or update your code according to new version.

2.x.x syntax

CanvasRenderService(width, height, chartCallback, type, chartJsFactory)

3.x.x

ChartJSNodeCanvas(options)

so in new version you’ve to use like

new ChartJSNodeCanvas({ width, height })
const { ChartJSNodeCanvas } = require('chartjs-node-canvas');
 
const chartCallback = (ChartJS) => {
    // Global config example: https://www.chartjs.org/docs/latest/configuration/
    ChartJS.defaults.global.elements.rectangle.borderWidth = 2;
};
 
const canvasRenderService = new ChartJSNodeCanvas({ width, height, chartCallback});

(async () => {
  const configuration = {
    type: "line",
    data: {
      labels: dates,
      datasets: [
        {
          label: "Total Cases",
          data: cases,
          backgroundColor: "rgba(255,255,0,0.1)",
          borderColor: "rgba(255,255,0,1)",
          borderWidth: 2,
          pointRadius: 2
        },

        {
          label: "Recoveries",
          data: recovered,
          backgroundColor: "rgba(0,255,0,0.1)",
          borderColor: "rgba(0,255,0,1)",
          borderWidth: 2,
          pointRadius: 2
        },
        {
          label: "Deaths",
          data: deaths,
          backgroundColor: "rgba(255,0,0,0.1)",
          borderColor: "rgba(255,0,0,1)",
          borderWidth: 2,
          pointRadius: 2
        }
      ]
    },
    options: {
      legend: {
        position: "bottom",
        labels: {
          fontColor: "rgb(255, 255, 255,1)",
          fontSize: 16
        }
      },
      scales: {
        xAxes: {
          grid: {
            display: false
          },
          ticks: {
            fontColor: "rgba(255, 255, 255, 1"
          }
        },
        yAxes: {
          grid: {
            lineWidth: 2,
            color: "rgba(255, 255, 255, 0.8)"
          },
          ticks: {
            fontColor: "rgba(255, 255, 255, 1"
          }
        }
      }
    }
  };
})
const image = await canvasRenderService.renderToBuffer( configuration );

Leave a comment