问题描述
我尝试使用 react-chartjs 2 制作饼图,它在桌面视图中工作正常,但在移动视图中,图例没有响应,它占用了太多空间,因此饼图的大小变得非常小.
我的代码:
function Chart(props: any) {
const option = {
tooltips: {enter image description here
callbacks: {
label: function (tooltipItem: any,data: any) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var Meta = dataset._Meta[Object.keys(dataset._Meta)[0]];
var total = Meta.total;
var currentValue = dataset.data[tooltipItem.index];
var percentage = parseFloat(
((currentValue / total) * 100).toFixed(1)
);
return currentValue + " (" + percentage + "%)";
},title: function (tooltipItem: any,data: any) {
return data.labels[tooltipItem[0].index];
},},legend: {
display: true,labels: {
fontSize: 12,position: "right",};
return (
<div className="chart">
<Pie data={props.ChartData} options={option} />
</div>
);
解决方法
您可以将您的 fontSize 对象设置为 ternery 运算符,它会检查小部件(或其他东西)以查看您是否在移动设备上并根据它返回正确的 fontSize
如果你想因为屏幕尺寸变化而实时更新它,你可以通过在 resizeEvent 监听器中改变图表选项本身来实现
var options = {
type: 'line',data: {
labels: ["Red","Blue","Yellow","Green","Purple","Orange"],datasets: [{
label: '# of Votes',data: [12,19,3,5,2,3],borderWidth: 1
},{
label: '# of Points',data: [7,11,8,7],borderWidth: 1
}
]
},options: {
legend: {
labels: {
fontSize: window.innerWidth > 350 ? 20 : 10
}
},scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx,options);
window.addEventListener('resize',() => {
if (window.innerWidth < 350) {
chart.options.legend.labels.fontSize = 10;
} else {
chart.options.legend.labels.fontSize = 20
}
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>