Chartjs-Angular 2 ng2-charts doughnut text in the middle disappears on mouse hover

2👍

You should rather create a plugin to draw the text, instead of drawing it on animation complete (this is the reason why the text flashes, as the animation onComplete function executes each time, when the chart detects any user interactions)

ᴘʟᴜɢɪɴ

Chart.plugins.register({
   afterDatasetsDraw: function(chart) {
      if (!chart.options.centerText) return;
      var ctx = chart.ctx,
         width = chart.canvas.width,
         height = chart.canvas.height;
      var fontSize = (height / 250).toFixed(2);
      ctx.font = fontSize + "em Verdana";
      ctx.textBaseline = "middle";
      ctx.fillStyle = "blue";
      var text = "Pass Rate 82%",
         textX = Math.round((width - ctx.measureText(text).width) / 2),
         textY = height / 2;
      ctx.fillText(text, textX, textY);
      ctx.restore();
   }
});

* text drawing code mostly adopted from this answer.
add this plugin inside ngOnInit() method, and then in your chart options add – centerText: true

also, you need to declare the variable Chart at the beginning of your component script, like so :

declare var Chart: any;

Leave a comment