本文介绍了在图表js-2中的反应中添加圆环图中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在甜甜圈饼图中添加一条短信。更具体地说,我想要这样的东西:

i want to add a text message inside my doughnut pie chart. To be more specific i want something like this:

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

I came across the same issue here in stack overflow by they use chart js in jquery and since i'm new to javascript i got confused. This is how i define my pie chart:

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


推荐答案

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

My example uses the property text on the data to specify the inner text:

const data = {
  labels: [...],
  datasets: [...],
  text: '23%'
};
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')
);
<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>

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

You'll have to scroll down a bit to see in when running the CodeSnippet due to some weird console error.

它在CodePen中正常工作,我写的地方:

It works properly in CodePen though, where I wrote it: http://codepen.io/anon/pen/OpdBOq?editors=1010

这篇关于在图表js-2中的反应中添加圆环图中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:17