简体   繁体   English

Chart.js显示无图表数据时的默认值

[英]Chart.js Default value when displaying no chart data

I'm using chart.Js to display my chart. 我正在使用chart.Js显示我的图表。 I'm getting my chart data via ajax and graphically render it to display the data, 我通过ajax获取我的图表数据并以图形方式呈现它以显示数据,

My question is, there are few cases when my Ajax returns nothing, and my Chart just display X axis and Y axis, with no data or no legend shown. 我的问题是,几乎没有什么情况下我的Ajax什么都不返回,我的图表只显示X轴和Y轴,没有显示数据或没有图例。 Is there any option to show default text ? 有没有显示默认文字的选项?

PS: I know I can add some conditional statement and display "No chart Div" and hide my "chart div", but i was some clean method to do the same. PS:我知道我可以添加一些条件语句并显示“No chart Div”并隐藏我的“chart div”,但我是一些干净的方法来做同样的事情。

You can try this solution: 你可以尝试这个解决方案:

if(1 < chartData.labels.length) {
    chart = new Chart(options.ctx).Line(chartData, options.chartOptions);
} else {
    options.ctx.font = "20px " + Chart.defaults.global.tooltipTitleFontFamily;
    options.ctx.textAlign = "center";
    options.ctx.textBaseline = "middle";
    options.ctx.fillStyle = Chart.defaults.global.scaleFontColor;
    options.ctx.fillText("No data in chart.", options.ctx.canvas.clientWidth / 2, options.ctx.canvas.clientHeight / 2);
}

This works for me I hope it helps 这对我有用,我希望它有所帮助

Chart.pluginService.register({
afterDraw: function (chart) {
                if (chart.data.datasets[0].data.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 = "20px normal 'Helvetica Nueue'";
                    ctx.fillText('No data to display', width / 2, height / 2);
                    ctx.restore();
                }

            }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM