DavideViolante / chartjs-plugin-labels

Plugin for Chart.js to display percentage, value or label in Pie or Doughnut.
MIT License
55 stars 18 forks source link

Does not work with chartjs-node-canvas (possible solution) #7

Closed Babbiorsetto closed 2 years ago

Babbiorsetto commented 2 years ago

chartjs-node-canvas allows you to use chart.js in Node. It even supports loading plugins, so I tried giving this plugin a spin. The way it works for plugins that rely on the global Chart object is it provides Chart in the initialization phase, assuming the plugins will just use it to register themselves and be done with it. When this falls apart though is when this plugin uses the global Chart object in the function renderToElement. The commit that introduced the use of the global Chart object in this fashion is 34db11744c258142753ab117d24dded4f41d7f58 at line 101. I modified this function to use a version of helpers which I had previously saved from the global object.

previously

Label.prototype.renderToElement = function (dataset, arg, element, index) {
  ...
  ctx.font = Chart.helpers.fontString(...)
}

modified

if (typeof Chart === 'undefined') {
  console.error('Cannot find Chart object.');
  return;
}
const helpers = Chart.helpers;
...
Label.prototype.renderToElement = function (dataset, arg, element, index) {
  ...
  ctx.font = helpers.fontString(...)
}

I will open a pull request to clarify the changes I made. Let me know if this sounds good enough to be included, otherwise I'll keep it to myself.

DavideViolante commented 2 years ago

v3.0.6 includes this change, updated on npmjs https://www.npmjs.com/package/chart.js-plugin-labels-dv