Adding a label to a donut chart in Chart.js shows all the values ​​in each chart.

I use Chart.js to draw a series of diagrams on my site, and I wrote a helper method to easily draw different graphs:

drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, midLabel) { var ctx = ctxElement; var data = { labels: ctxDataLabels, datasets: ctxDataSets }; 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); ctx.font = fontSize + "em sans-serif"; ctx.textBaseline = "middle"; var text = midLabel, textX = Math.round((width - ctx.measureText(text).width) / 2), textY = height / 2; ctx.fillText(text, textX, textY); ctx.save(); } }); var chart = new Chart(ctx, { type: ctxType, data: data, options: { legend: { display: false }, responsive: true } }); } 

The last parameter of the drawChart () method contains a label that should be added in the middle of the chart. The Chart.pluginService.register part is the code that draws the label. The problem is that when I execute the drawChart method several times (in my case three times) and put a label on each chart when the method is executed, all three labels are displayed on top of each other on each chart. I need to display each label in the corresponding chart. All other parameters are processed correctly, except for the label.

How do I achieve this?

+5
source share
1 answer

A simple workaround is to add another parameter to your function to distinguish your charts from each other.

I decided to use a chart id for this, so you are sure you will not affect the other.

First you need to slightly modify your function:

 // !! // Don't forget to change the prototype // !! function drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, midLabel, id) { var ctx = ctxElement; var data = { labels: ctxDataLabels, datasets: ctxDataSets }; Chart.pluginService.register({ afterDraw: function(chart) { // Makes sure you work on the wanted chart if (chart.id != id) return; // From here, it is the same as what you had var width = chart.chart.width, height = chart.chart.height, ctx = chart.chart.ctx; // ... } }); // ... } 

Now, when you call your function, do not forget about id:

 // ids need to be 0, 1, 2, 3 ... drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 1", 0); drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 2", 1); drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 3", 2); 

You can see a fully working example of this script (with 3 diagrams), and here is a preview:

enter image description here

+1
source

Source: https://habr.com/ru/post/1264031/


All Articles