ChartjsNodeCanvas icon indicating copy to clipboard operation
ChartjsNodeCanvas copied to clipboard

Problem using chartjs-plugin-datalabels (and recommended fix)

Open Whobeu opened this issue 2 years ago • 2 comments

I am current using using Chart.js 3.9.1. I was having a problem with chartjs-plugin-datalabels not working correctly after an initial call of 'new ChartJSNodeCanvas'. Digging through the chartjs-plugin-datalabels code I found there was an issue with 'instanceof' not working correctly on the subsequent calls. In my code, every call to my graphing method called 'new ChartJSNodeCanvas'. I was able to work around the issue by making a single global call to 'new ChartJSNodeCanvas' in my module and reusing it. It also had the side benefit of reducing the overhead of creating new canvases.

I reported the issue to the chartjs-plugin-datalabels maintainer and I was pointed to a similar issue at https://github.com/chartjs/chartjs-plugin-datalabels/issues/251. Reading through the thread it seems there is a minor change needed to the Chart.js require statement to fix the issue. I edited line 149 of the chartjs-node-canvas index.js and changed

const chartJs = require('chart.js');

to

const chartJs = require('chart.js/auto');

With this change, my original code works fine. I will probably leave my code with the single global call as it does reduce the overhead of creating multiple canvases. But this change to the require statement appears to be something needed with the 3.x.x Chart.js to register the controllers, elements, scales and plugins you are going to use, as documented at https://www.chartjs.org/docs/latest/getting-started/integration.html.

Whobeu avatar Sep 10 '22 14:09 Whobeu

I'm running into the same issue and can confirm that above fix solves it. Would be great to have this fix included soon.

mj-mueller avatar Sep 26 '22 10:09 mj-mueller

Yep this is the fix. Can we get a PR? 🙏🏻

askdesigners avatar Mar 02 '23 15:03 askdesigners