I would like to make a doughnut chart using Chart.Js library, with text in the center of the doughnut and the percentage on each segment.
The segments on the chart are generated dynamically.
So I look through Stackoverflow to look for solution, and combined 2 that I found:
How to create a donut chart like this in chart.js How to add text inside the doughnut chart using Chart.js?
and combine into the following javascript:
Chart.defaults.derivedDoughnut = Chart.defaults.doughnut;
var helpers = Chart.helpers;
var customDN = Chart.controllers.doughnut.extend({
draw: function(ease) {
Chart.controllers.doughnut.prototype.draw.call(this, ease);
if (this.chart.config.options.elements.center) {
//Get ctx from string
var ctx = this.chart.chart.ctx;
//Get options from the center object in options
var centerConfig = this.chart.config.options.elements.center;
var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = centerConfig.text;
var color = centerConfig.color || '#000';
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding/100) * (this.chart.innerRadius * 2)
//Start with a base font of 30px
ctx.font = "30px " + fontStyle;
//Get the width of the string and also the width of the element minus 10 to give it 5px side padding
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (this.chart.innerRadius * 2) - sidePaddingCalculated;
// Find out how much the font can grow in width.
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(20 * widthRatio);
var elementHeight = (this.chart.innerRadius * 2);
// Pick a new font size so it will not be larger than the height of label.
var fontSizeToUse = Math.min(newFontSize, elementHeight);
//Set font settings to draw it correctly.
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((this.chart.chartArea.left + this.chart.chartArea.right) / 2);
var centerY = ((this.chart.chartArea.top + this.chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse+"px " + fontStyle;
ctx.fillStyle = color;
//Draw text in center
ctx.fillText(txt, centerX, centerY);
//labels
var chart = this.chart;
var chartArea = chart.chartArea;
var opts = chart.options;
var meta = this.getMeta();
var arcs = meta.data;
for (i in arcs){
var arcctx = arcs[i]._chart.ctx;
var view = arcs[i]._view;
var sa = view.startAngle;
var ea = view.endAngle;
var opts = arcs[i]._chart.config.options;
var labelPos = arcs[i].tooltipPosition();
var segmentLabel = view.circumference / opts.circumference*100;
arcctx.fillStyle = view.borderColor;
arcctx.font = "1px" + fontStyle;
arcctx.fillText(segmentLabel.toFixed(0) + "%", labelPos.x, labelPos.y);
}
}
}
});
but my outcome is outcome image
I tried fixing the font of the arc, but it still does not work. It seems to utilize the font set for the text in the center of the doughnut.
Can someone tell me what did I do wrong here, how do I set the font size of the arc and text in the center of the doughnut differently? Thanks!