SeanSobey / ChartjsNodeCanvas

A node renderer for Chart.js using canvas.
MIT License
228 stars 70 forks source link

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

Open Whobeu opened 1 year ago

Whobeu commented 1 year ago

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.

mj-mueller commented 1 year ago

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

askdesigners commented 1 year ago

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