How to Add Text Inside the Doughnut Chart Using Chart.Js

How to add text inside the doughnut chart using Chart.js?

You have to modify the code like:
in chart.Doughnut.defaults

labelFontFamily : "Arial",
labelFontStyle : "normal",
labelFontSize : 24,
labelFontColor : "#666"

and then in function drawPieSegments

ctx.fillText(data[0].value + "%", width/2 - 20, width/2, 200);

See this pull: https://github.com/nnnick/Chart.js/pull/35

here is a fiddle http://jsfiddle.net/mayankcpdixit/6xV78/ implementing the same.

How to add text in centre of the doughnut chart using Chart.js?

It is certainly possible to do something like this in Chart.js v2.x

I think the nicest way to do it is by using a plugin. In fact, Cmyker awnser to the question you linked to even updated his posts to show how this would work in Charts.js v2.x

See his fiddle: https://jsfiddle.net/cmyker/ooxdL2vj/

and the corresponding plugin definition:

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 = "75%",
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;

ctx.fillText(text, textX, textY);
ctx.save();
}
});

Add Text to Doughnut Chart - ChartJS

I've tried to append text to the center

You're appending elements inside of the canvas tag. That's only displayed as a fallback when your browser lacks canvas support.

What you're looking for is using the canvas getContext method.

Jsfiddle example

Adapted to what you provided, it would go something like this:

var centerX = chart.width / 2;
var centerY = chart.height / 2;

chart.fillStyle = 'black';
chart.font = '200px';
chart.textAlign = 'center';
chart.fillText(selector, centerX, centerY);

You may need to offset centerX or centerY depending on how the width of your doughnut charts is calculated.



Related Topics



Leave a reply



Submit