Text in the middle of a doughnut with 2amigos/yii2-chartjs-widget

I everybody,

i use 2amigos/yii2-chartjs-widget in my project. Now i draw doughnuts with a text inside. It works fine, but if i display a legend on left or right side, the text is not in the middle of the doughnut.

grafik

My code:

                'plugins' =>
                    new \yii\web\JsExpression('
                    [{
                        id: \'text\',
                        afterDatasetsDraw: function(chart, a, b) {
                            var width = chart.width,
                            height = chart.height,
                            ctx=chart.ctx;
                            ctx.restore();
                            var fontSize = (height / 50).toFixed(2);
                            ctx.font = fontSize + "em sans-serif";
                            ctx.textBaseline = "middle";
                            ctx.fillStyle ="rgb(200,200,200)";
                
                            var text = "'.$numVal.'",
                            textX = Math.round((width - ctx.measureText(text).width) / 2),
                            textY = height / 2;
                
                            ctx.fillText(text, textX, textY);
                            ctx.save();
                        }
                    }]')

I hope ones of you has a tip for me.

Thanks very much…

Now i found a solution. I used chart.chartArea.right to set the width instead chart.width. No it works…

3 Likes