如果数据集为空,Chart.js饼图显示“无数据”

问题描述 投票:0回答:1

如果饼图中没有数据,我试图显示“没有要显示的数据”。如果图表是一行,这可以正常工作,但如果它是一个饼图,它就不起作用。我已经包含了插件,但我仍然得到了所需的输出。让我知道我在哪里犯错误

Chart.plugins.register({
	afterDraw: function(chart) {
  	if (chart.data.datasets.length === 0) {
    	// No data is present
      var ctx = chart.chart.ctx;
      var width = chart.chart.width;
      var height = chart.chart.height
      chart.clear();
      
      ctx.save();
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = "16px normal 'Helvetica Nueue'";
      ctx.fillText('No data to display', width / 2, height / 2);
      ctx.restore();
    }
  }
});

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
	type: 'line',
  data: {
  	labels: ['Jan', 'Feb', 'Mar', 'Apr'],
    datasets: []
  }
});

var ctx2 = document.getElementById('chart2').getContext('2d');
var myChart2 = new Chart(ctx2, {
	type:'pie',
  data:{
  	labels:['Jan', 'Feb', 'Mar', 'Apr'],
    datasets:[{
    	data:[],
      backgroundColor: ['red','blue','green','yellow']
    }]
  }
});

var ctx3 = document.getElementById('chart3').getContext('2d');
var myChart3 = new Chart(ctx3, {
	type: 'pie',
  data: {
  	labels: ['Jan', 'Feb', 'Mar', 'Apr'],
    datasets: []
  }
});
<canvas id="chart"></canvas>
<canvas id="chart2"></canvas>
<canvas id="chart3"></canvas>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
javascript chart.js
1个回答
0
投票

试试这个:

var ctx2 = document.getElementById('chart2').getContext('2d');
var myChart2 = new Chart(ctx2, {
    type:'pie',
    data:{
      labels:['Jan', 'Feb', 'Mar', 'Apr'],
      datasets:[]
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.