如何使用react-chartjs-2.js 将文本放入圆环图中?
P粉378264633
P粉378264633 2024-03-30 15:14:29
[React讨论组]

当图表的标题位于顶部且标签位于圆环图右侧时,如何使用react-chartjs-2.js 和 Typescript 将文本放入圆环图中。到目前为止我找到的解决方案似乎不适用于侧面的标签或 React/TS。

这就是我现在拥有的:

...

setOptions({
   responsive: true,
   plugins: {
     legend: {
       position: 'right',
       rtl : true,
       labels: {
         usePointStyle: true,
         pointStyle: 'circle',
       }
     },
     title: {
       display: true,
       text: 'Title',
       font: {
         size: 25,
       }
     }
   },
});
    
setPlugins ({
    id: "tooltipLine",
    beforeDraw: function(chart) {
      var width = chart.width,
      height = chart.height,
      ctx = chart.ctx;
      ctx.restore();
      var fontSize = (height / 160).toFixed(2);
      ctx.font = fontSize + "em sans-serif";
      ctx.textBaseline = "top";
      var text = "Foo-bar",
      textX = Math.round((width - ctx.measureText(text).width) / 2),
      textY = height / 2;
      ctx.fillText(text, textX, textY);
      ctx.save();
    }
})
<Doughnut id="pieChart" data={data} options={options} plugins={[plugins] as any}/>

但这只是使文本位于整个画布的中间,而不是甜甜圈的中间。

P粉378264633
P粉378264633

全部回复(1)
P粉872101673
const plugins = [{
        beforeDraw: function(chart) {
            var width = chart.width,
                height = chart.height,
                ctx = chart.ctx;
            ctx.restore();
            var fontSize = (height / 160).toFixed(2);
            ctx.font = fontSize + 'em sans-serif';
            ctx.textBaseline = 'top';

            // Draw "Total" on the first line
            var text1 = 'Total';
            var textX1 = Math.round((width - ctx.measureText(text1).width) / 2);
            var textY1 = height / 2.5;
            ctx.fillText(text1, textX1, textY1);

            // Draw the number on the second line
            var text2 = totalStatusCountRef.current;
            var textX2 = Math.round((width - ctx.measureText(text2).width) / 2);
            var textY2 = height / 1.9;
            ctx.fillText(text2, textX2, textY2);

            ctx.save();
        }
    }];
     
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号