【问题标题】:Overlay text message on top of a chart在图表顶部覆盖文本消息
【发布时间】:2019-03-16 05:39:29
【问题描述】:

是否有任何选项可以在图表顶部添加覆盖文本消息(如附件图像)?或者你能给我任何参考来实现它吗?

  • 没有消息

  • 有消息

【问题讨论】:

    标签: chart.js react-chartjs


    【解决方案1】:

    我找到了几乎相同的问题和答案。它使用圆环图。

    Add text inside doughnut chart from chart js-2 in react

    然后我把它从圆环图改为折线图。它奏效了。

    https://codepen.io/yzono/pen/ZPoQKg

    import React from 'react';
    import ReactDOM from 'react-dom';
    import {Line} from 'react-chartjs-2';
    
    var originalDoughnutDraw = Chart.controllers.line.prototype.draw;
    Chart.helpers.extend(Chart.controllers.line.prototype, {
      draw: function() {
        originalDoughnutDraw.apply(this, arguments);
    
        var chart = this.chart;
        var width = chart.chart.width,
            height = chart.chart.height,
            ctx = chart.chart.ctx;
    
        var fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.fillStyle = "black";
        ctx.textBaseline = "middle";
    
        var text = chart.config.data.text,
            textX = Math.round((width - ctx.measureText(text).width) / 2),
            textY = height / 2;
    
        ctx.fillText(text, textX, textY);
      }
    });
    
    const data = {
          labels: [
            "10/04/2018",
            "10/05/2018",
            "10/06/2018",
            "10/07/2018",
            "10/08/2018",
            "10/09/2018",
            "10/10/2018",
            "10/11/2018",
            "10/12/2018",
            "10/13/2018"
          ],
          datasets: [
            {
              label: "Temperature",
              data: [22, 19, 27, 23, 22, 24, 17, 25, 23, 24],
              fill: true,
              borderColor: "#ffebee",
              backgroundColor: "#ffebee"
            }
          ],
          text: "$3,881.38"
    };
    
    class DonutWithText extends React.Component {
    
      render() {
        return (
          <div>
            <h2>aReact Doughnut with Text Example</h2>
            <Line data={data} />
          </div>
        );
      }
    };
    
    ReactDOM.render(
      <DonutWithText />,
      document.getElementById('root')
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多