Chart.js Default value when displaying no chart da

2019-07-03 15:03发布

I'm using chart.Js to display my chart. I'm getting my chart data via ajax and graphically render it to display the data,

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. 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.

2条回答
对你真心纯属浪费
2楼-- · 2019-07-03 15:41

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);
}
查看更多
神经病院院长
3楼-- · 2019-07-03 15:44

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();
                }

            }
});
查看更多
登录 后发表回答