繁体   English   中英

在 React-Chartjs-2 框的圆环图中添加文本以做出反应

[英]Add text inside the Doughnut chart of the React-Chartjs-2 box to react

我创建了一个圆环图,它可以正常工作,但现在我需要在其中心显示数字 45,例如。

我应该在哪里指示要显示的文本和坐标? 在图表的选项中?

我正在使用反应组件

class DoughnutChart extends React.Component {

  render() {
    const data = {
      datasets: [{
      data: [],
      backgroundColor: [
        '#999',
        '#eee'
      ]
    }],
     text: '45'
  };
    return (
       <Doughnut data={data} />
    );
  }
};

export default DoughnutChart;

编辑

我找到了这个插件,但我找不到它如何应用于反应组件

//Plugin for center text
Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,
    height = chart.chart.height,
    ctx = chart.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();
  }
});

谢谢你的帮助。

从我从react-chartjs-2看到的它只有这些属性:

data: (PropTypes.object | PropTypes.func).isRequired,
width: PropTypes.number,
height: PropTypes.number,
id: PropTypes.string,
legend: PropTypes.object,
options: PropTypes.object,
redraw: PropTypes.bool,
getDatasetAtEvent: PropTypes.func,
getElementAtEvent: PropTypes.func,
getElementsAtEvent: PropTypes.func
onElementsClick: PropTypes.func, // alias for getElementsAtEvent (backward compatibility)

它们似乎都不是您可以传入以在中间显示您的号码的文本。 您可以使用图例道具并操纵为图例创建的对象,以使用 css 移动它,或者在渲染中使用另一个 div 来显示数字,然后将其设置为图表内的样式。

另一种方法是将 Donut 组件包装在一个 div 中,并在该 div 中包含另一个包含文本的子组件,如下所示:

    return( 
    <div className='wrapper'> 
        <div className='chart-number'>{this.state.text}</div>
        <Doughnut data={data} />
    </div>)

在您的 css 中,您将必须弄清楚如何将图表编号 div 放置在包含图表的包装 div 的中间。

如果您刚刚开始使用这个库,也许可以寻找一个适合您需求的不同的库,这样您就不必围绕它编写代码了!

希望这可以帮助 :)

编辑 1:

据我Chart.pluginService.register ,您可能需要以某种方式将Chart.pluginService.register代码连接到您的图形对象,即<Doughnut />组件,然后它会在重绘之前进行计算。

我不相信 React Chart JS 有这个选项可用。 但是,有一些自定义插件允许您在圆环图内插入自定义数据标签。 请参阅此文档以了解如何完成此操作。

ChartJS 插件数据标签

我试过了,它奏效了

import { Doughnut } from "react-chartjs-2";

function DoughnutChart() {

 const data = {...}

 const options = {...}

 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";
          var text = "Foo-bar",
          textX = Math.round((width - ctx.measureText(text).width) / 2),
          textY = height / 2;
          ctx.fillText(text, textX, textY);
          ctx.save();
     } 
   }]



  return (
   
        <Doughnut 
          type="doughnut" 
          data={data} 
          options{options} 
          plugins={plugins} 
         />
  );
}

export default DoughnutChart;

这是一个简单的解决方案:

步骤 01:在您的选项中添加此选项

options: {
        centerText: {
            display: true,
            text: `90%`
        }
      .....
      .....

步骤 02:创建一个新方法 drawInnerText

drawInnerText = (chart) => {

    var width = chart.chart.width,
        height = chart.chart.height,
        ctx = chart.chart.ctx;

    ctx.restore();
    var fontSize = (height / 114).toFixed(2);
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "middle";

    var text = chart.config.options.centerText.text,
        textX = Math.round((width - ctx.measureText(text).width) / 2),
        textY = height / 2;

    ctx.fillText(text, textX, textY);
    ctx.save();
}

步骤 03:调用 drawInnerText

componentWillMount() {
        Chart.Chart.pluginService.register({
            beforeDraw: function (chart) {                    
                if (chart.config.options.centerText.display !== null &&
                    typeof chart.config.options.centerText.display !== 'undefined' &&
                    chart.config.options.centerText.display) {
                    this.drawInnerText(chart);
                }
            },
        });
    }
function DoughnutChart({ data = {} }) {
 return (
   <Doughnut
     data={format(dataObj)}
     plugins={[
      {
        beforeDraw(chart) {
         const { width } = chart;
         const { height } = chart;
         const { ctx } = chart;
         ctx.restore();
         const fontSize = (height / 160).toFixed(2);
         ctx.font = `${fontSize}em sans-serif`;
         ctx.textBaseline = 'top';
         const { text } = "23";
         const textX = Math.round((width - ctx.measureText(text).width) / 2);
         const textY = height / 2;
         ctx.fillText(text, textX, textY);
         ctx.save();
       },
     },
   ]}
 />);

}

我以前尝试过 Jays Answer,但现在它不再起作用了。 您需要在 plugins 数组中指定一个 id。

 const plugins = [{
 id : 'here comes your id for the specific plugin',
 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();
 } 

}]

我已经尝试过 Jay 的回答,起初它没有用,所以我不得不对其进行一些更新,现在它可以正常工作了。

const plugins = {[
{
  id:"Id here",
  beforeDraw:function(chart:any) {
    let ctx = chart.ctx;
    let xAxis = chart.scales.x;
    let yAxis = chart.scales.y;
    let maxValue = Math.max(...chart.data.datasets[0].data);
    let minValue = Math.min(...chart.data.datasets[0].data);
    ctx.save();
    ctx.textAlign = 'center';
    ctx.font = '14px Roboto';
    ctx.fillStyle = 'blue';
    ctx.textAlign = 'left';
    ctx.fillText('Text1 = ', xAxis.left , yAxis.top + 15);
    ctx.fillText('Text2 = ', xAxis.left , yAxis.top + 40);
    ctx.fillText(maxValue + '°C', xAxis.left + 200, yAxis.top + 15);
    ctx.fillText(minValue + '°C', xAxis.left + 200, yAxis.top + 40);
    ctx.restore();
 },

}, ]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM