I have a webpage using Chart.js. On this page, I draw three donut charts. In the middle of each chart, I want to show the percentage of the filled donut. I currently have the following code that can be seen in this Fiddle .
function setupChart(chartId, progress) { var canvas = document.getElementById(chartId); var context = canvas.getContext('2d'); var remaining = 100 - progress; var data = { labels: [ 'Progress', '', ], datasets: [{ data: [progress, remaining], backgroundColor: [ '#8FF400', '#FFFFFF' ], borderColor: [ '#8FF400', '#408A00' ], hoverBackgroundColor: [ '#8FF400', '#FFFFFF' ] }] }; var options = { responsive: true, maintainAspectRatio: false, scaleShowVerticalLines: false, cutoutPercentage: 80, legend: { display: false }, animation: { onComplete: function () { var xCenter = (canvas.width / 2) - 20; var yCenter = canvas.height / 2 - 40; context.textAlign = 'center'; context.textBaseline = 'middle'; var progressLabel = data.datasets[0].data[0] + '%'; context.font = '20px Helvetica'; context.fillStyle = 'black'; context.fillText(progressLabel, xCenter, yCenter); } } }; Chart.defaults.global.tooltips.enabled = false; var chart = new Chart(context, { type: 'doughnut', data: data, options: options }); }
The graph is working. But the problem is rendering the label. The label is not vertically and horizontally centered in the middle of the donut. The position of the cue also changes based on the screen resolution. You can see the position of the label change by changing the size of the frame that is displayed in the diagrams in Fiddle .
My question is, how can I sequentially position the percentage in the middle of the donut? My page is a responsive page, therefore it is important to have consistent positioning. But I'm not sure what else to do. I feel that the textAlign
and textBaseline
not working, or I do not understand their use.
Thanks!
source share