Center text on doughnut chart that has a title with position top or bottom

78 views
Skip to first unread message

Mike Poole

unread,
Apr 27, 2020, 2:40:17 PM4/27/20
to Chart.js User Discussion
I have added the plugin to my ChartJS doughnut chart (below) to add the center text and this all works fine

My issue is that if I add a title to the chart (position either `'top'` or `'bottom'` then the text does not center as the height of the canvas is the doughnut AND the title.

Is there a way to remove take into account the height of the title when calculating the `textY` (height/2)? There do not appear to be any available properties available to offset the center to correctly place the text

Many thanks

Mike

     afterDraw: function (chart, options) {
                            var newFillText = '25%';
                            if (chart.options.centertext) {
                                var width = chart.chart.width,
                                    height = chart.chart.height,
                                    ctx = chart.chart.ctx;
                                ctx.restore();
                                var fontSize = (height / 130).toFixed(2); //was 114
                                ctx.font = fontSize + "em sans-serif";
                                ctx.textBaseline = "middle";
                                var text = chart.options.centertext,
                                    textX = Math.round((width - ctx.measureText(newFillText).width) / 2),
                                    textY = height / 2;
                                ctx.fillText(newFillText, textX, textY);
                                ctx.save();
                            }
                        },
Reply all
Reply to author
Forward
0 new messages