ChartJS 在给charjs的甜甜圈中间发短信

zbwhf8kr  于 2023-05-17  发布在  Chart.js
关注(0)|答案(1)|浏览(125)

我每个人,
我在我的项目中使用了2amigos/yii 2-chartjs-widget。现在我画一个里面有文字的甜甜圈。它工作正常,但如果我在左侧或右侧显示图例,文本就不在甜甜圈的中间。
enter image description here
我的代码:

'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();
                        }
                    }]')

我希望你们中有人能给我一个提示。
非常感谢...

xfb7svmp

xfb7svmp1#

你不应该使用图表dom元素的大小,而应该使用图表区域。

[{
  id: 'text',
  afterDatasetsDraw: function(chart) {
    const {ctx, chartArea} = chart; 
    const {left, top, width, height} = chartArea;
    ctx.save();
    var fontSize = (height / 50).toFixed(2); // In my opinion this should be reevaluated
    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, left + textX, top + textY);
    ctx.restore();
  }
}]

相关问题