0

I have tried the solution posted in this question to put a text inside (in the middle, vertical and horizontally aligned) of a donut chart and it works almost perfectly. The issue is that every time the mouse hovers over the chart, the text flashes. It seems like this happens because when the mouse hovers over the chart, the function that handles the text writing is called again.

My component code is something like:

imports ....

@Component({
    selector: 'my-component-app',
    templateUrl: '../views/my-component.component.html',
    styleUrls: ['../styles/my-component.component.css']
})

export class MyComponent implements OnInit {
    chartOptions;
    chartLabales;
    chartData;

    ngOnInit(): {
        this.chartData = ....
        this.chartOptions = ....
    }
}

Any idea about how to solve this problem ? Thanks

Gerardo Tarragona
  • 1,185
  • 4
  • 15
  • 28

1 Answers1

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;
ɢʀᴜɴᴛ
  • 32,025
  • 15
  • 116
  • 110