iTikoz
iTikoz

Reputation: 113

Dynamic multiple charts in chart.js with dynamic data inside them

I am having an issue showing the percentage inside the doughnut chart in a dynamic way. I would like to have multiple dynamic charts in the same page (unknown number).

I have found a solution to create the dynamic charts but each time I create a chart - I feed the text in the middle of the doughnut but it is shown on the others as well

enter image description here

I used this to put the percentage in the middle of the doughnut

Chart.pluginService.register({
    beforeDraw: function(chart) {
      var width = chart.chart.width,
          height = chart.chart.height,
          ctx = chart.chart.ctx;

      ctx.restore();
      var fontSize = (height / 114).toFixed(2); // default 114
      ctx.font = fontSize + "em sans-serif";
      ctx.textBaseline = "middle";

      var text = $var + "%",
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = height / 2;

      ctx.fillText(text, textX, textY);
      ctx.save();
    }
});

Upvotes: 1

Views: 1092

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

In your plugin, change this line of code :

var text = $var + "%",

to this :

var text = chart.options.centerText + "%",

..and then, set centerText property to a data value in your chart options (for each of your charts)

see a working example

Upvotes: 1

Related Questions