Bel*_*cia 14 javascript pie-chart reactjs react-chartjs
我创建了一个圆环图,它可以正常工作,但现在我需要在其中心显示数字 45,例如。
我应该在哪里指定要显示的文本和坐标?在图表的选项中?
我正在使用反应组件
class DoughnutChart extends React.Component {
render() {
const data = {
datasets: [{
data: [],
backgroundColor: [
'#999',
'#eee'
]
}],
text: '45'
};
return (
<Doughnut data={data} />
);
}
};
export default DoughnutChart;
Run Code Online (Sandbox Code Playgroud)
编辑
我找到了这个插件,但我找不到它如何应用于反应组件
//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();
}
});
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助。
小智 14
我尝试过这个并且有效
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;
Run Code Online (Sandbox Code Playgroud)
从我从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)
Run Code Online (Sandbox Code Playgroud)
它们似乎都不是您可以传递以在中间显示您的号码的文本。您可以使用 legend 属性并操纵为图例创建的对象,以使用 css 移动它,或者在渲染中使用另一个 div 来显示数字,然后将其设置为图表内的样式。
另一种方法是将 Donut 组件包装在一个 div 中,并在该 div 中包含另一个包含文本的子组件,如下所示:
return(
<div className='wrapper'>
<div className='chart-number'>{this.state.text}</div>
<Doughnut data={data} />
</div>)
Run Code Online (Sandbox Code Playgroud)
在你的CSS中,你必须弄清楚如何将图表编号div放置在包装器div的中间,其中将包含图表。
如果您刚刚开始使用这个库,也许可以寻找一个适合您需求的不同库,这样您就不必围绕它编写代码!
希望这可以帮助 :)
编辑1:
据我所知,您可能需要Chart.pluginService.register以某种方式将代码连接到作为<Doughnut />组件的图形对象,然后它将在重绘之前进行计算。