I'm using Chart.js to draw a series of charts on my site and I've written a helper method to draw different charts easily:
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 for the drawChart() method contains the 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 multiple times (in my case three times) and supply the label of each chart in the method executions, all three labels are shown on top of each other on each chart. I need to display each label in the corresponding chart. All other parameters are handled correctly, except for the label.
How do I achieve that?