如果没有可用数据,可以使用global plugin绘制“无可用数据”文本。
Chart.plugins.register({
afterDraw: chart => {
if (chart.data.datasets[0].data.length === 0) {
var ctx = chart.chart.ctx;
ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = "22px Arial";
ctx.fillStyle = "gray";
ctx.fillText('No data available', chart.chart.width / 2, chart.chart.height / 2);
ctx.restore();
}
}
});
new Chart(document.getElementById('canvas'), {
type: 'bar',
data: {
labels: [],
datasets: [{
data: []
}]
},
options: {
legend: {
display: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" height="80"></canvas>