在图表js-2中的反应中添加圆环图中的文本

时间:2017-03-13 08:33:43

标签: javascript reactjs pie-chart react-chartjs

我想在甜甜圈饼图中添加一条短信。更具体一点,我想要这样的东西: enter image description here

我在堆栈溢出中遇到了同样的问题,他们在jquery中使用图表js,因为我是javascript的新手,我感到很困惑。这是我定义饼图的方式:

<Doughnut
            data={sectorsData}
            width={250}
            height={250}
            options={{
              legend: {
                display: false
              },
              maintainAspectRatio: false,
              responsive: true,
              cutoutPercentage: 60
            }}
          />

1 个答案:

答案 0 :(得分:5)

我的示例使用数据属性text来指定内部文本:

const data = {
  labels: [...],
  datasets: [...],
  text: '23%'
};

&#13;
&#13;
import React from 'react';
import ReactDOM from 'react-dom';
import {Doughnut} from 'react-chartjs-2';

// some of this code is a variation on https://jsfiddle.net/cmyker/u6rr5moq/
var originalDoughnutDraw = Chart.controllers.doughnut.prototype.draw;
Chart.helpers.extend(Chart.controllers.doughnut.prototype, {
  draw: function() {
    originalDoughnutDraw.apply(this, arguments);
    
    var chart = this.chart.chart;
    var ctx = chart.ctx;
    var width = chart.width;
    var height = chart.height;

    var fontSize = (height / 114).toFixed(2);
    ctx.font = fontSize + "em Verdana";
    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: [
		'Red',
		'Green',
		'Yellow'
	],
	datasets: [{
		data: [300, 50, 100],
		backgroundColor: [
		'#FF6384',
		'#36A2EB',
		'#FFCE56'
		],
		hoverBackgroundColor: [
		'#FF6384',
		'#36A2EB',
		'#FFCE56'
		]
	}],
  text: '23%'
};

class DonutWithText extends React.Component {

  render() {
    return (
      <div>
        <h2>React Doughnut with Text Example</h2>
        <Doughnut data={data} />
      </div>
    );
  }
};

ReactDOM.render(
  <DonutWithText />,
  document.getElementById('root')
);
&#13;
<script src="https://gor181.github.io/react-chartjs-2/common.js"></script>
<script src="https://gor181.github.io/react-chartjs-2/bundle.js"></script>

<div id="root">
</div>
&#13;
&#13;
&#13;

由于一些奇怪的控制台错误,您在运行CodeSnippet时必须向下滚动一下才能看到。

它在CodePen中正常工作,我写的是:http://codepen.io/anon/pen/OpdBOq?editors=1010