Search code examples
node.jschart.jschartjs-plugin-annotation

ChartJSNodeCanvas plugin chartjs-plugin-annotation creates error: HTMLCanvasElement is not defined


I want to create my chart as png on the server.
The X axe is based on time, therefore I need the date adapter.

const chartJSNodeCanvas = new ChartJSNodeCanvas({
    width: 512,
    height: 400,
    backgroundColour: "white",
    plugins: {
      modern: ['chartjs-plugin-annotation'],
      globalVariableLegacy: ["chartjs-adapter-date-fns"],
    },
  });
const image = await chartJSNodeCanvas.renderToBuffer(config);
fs.writeFileSync("c:/wswin/mychart.png", image);

then I get the error:

error: HTMLCanvasElement is not defined HTMLCanvasElement is not defined 
{"stack":"ReferenceError: HTMLCanvasElement is not defined\n    
at isImageOrCanvas (C:\\Users\\baumanng\\Documents\\Visual Studio Code\\wetterstation\\node_modules\\chartjs-plugin-annotation\\dist\\chartjs-plugin-annotation.js:334:57)\n
....

If I comment the plugin out

//modern: ['chartjs-plugin-annotation'],

then it is working, but the annotations are not visible.
On the local browser the config data is ok with annotations.

the packages are installed:

    "chartjs": "^0.3.24",
    "chartjs-adapter-date-fns": "^1.1.0-beta.1",
    "chartjs-node-canvas": "^4.1.6",
    "chartjs-plugin-annotation": "^1.3.1",

Where is my mistake? Thanks for help.


Solution

  • This issue is resolved in version 1.4.0 of the annotation plugin. So you just need to update to fix it