2amigos / yii2-chartjs-widget

ChartJs Widget For Yii2
https://2amigos.us
Other
109 stars 67 forks source link

text in the middle of a doughnut #57

Closed saschahaendle closed 1 year ago

saschahaendle commented 1 year ago

Hi everybody,

how can i add a text in the middle of a doughnut? I think i must do this with plugins, but don't know how the best practice.

Now i found a solution. You should really read the documentation first :-)

It works fine. But if i have a doughnut with a legend left or right, the text always shown in the middle of the canvas, but not in the middle of the doughnut.

grafik

This is my code:

` 'plugins' =>

                new \yii\web\JsExpression('
                [{
                    id: \'text\',
                    beforeDraw: 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...

saschahaendle commented 1 year ago

Now i found a solution. I used now the right-attribute from chartArea instead the width from chart.

var width = chart.width,

now

var width = chart.chartArea.right