在图表上方覆盖文字消息

时间:2019-03-16 05:39:29

标签: chart.js react-chartjs

是否有其他选项可在图表顶部(如附件图像)添加叠加文字消息?还是可以给我一些实现它的参考?

  • 没有消息

enter image description here

  • 有消息

enter image description here

1 个答案:

答案 0 :(得分:0)

我发现了几乎相同的问题和答案。它使用甜甜圈图。

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')
);