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
Why Does JavaScript Hoist Variables
Finding Longest String in Array
Dc.Js - How to Create a Row Chart from Multiple Columns
Correct Way to Handle Conditional Styling in React
Finding Element's Position Relative to the Document
How to Set a Js Object Property Name from a Variable
Why Do We Need to Install Gulp Globally and Locally
Retrieving Binary File Content Using JavaScript, Base64 Encode It and Reverse-Decode It Using Python
Method for Streaming Data from Browser to Server via Http
Why Define an Anonymous Function and Pass It Jquery as the Argument
Canvas Todataurl() Returns Blank Image
Associative Array Versus Object in JavaScript
How to Call Fromlatlngtodivpixel in Google Maps API V3