Home > Enterprise >  Chart JS - Title missing when clearing canvas if no data is available
Chart JS - Title missing when clearing canvas if no data is available

Time:12-16

EDIT - Answer below worked fine, all I did aside from removing chart.clear() was to hide the legend and the x/y axes.

Any ideas what may be causing the blurry text now, though?

enter image description here

I'm sure I'm doing something remarkably silly, but I can't seem to figure this out.

I have the following global plugin that will display a "No data to display" message when applicable:

Chart.plugins.register({
  afterDraw: function(chart, args, options) {
    if (chart.data.datasets.every(dataSetContainsNoData)) {
        debugger;
        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.fillText('No data to display', width / 2, height / 2);
    }
}
});

This works fine enter image description here

However, I would like to keep the title of this chart showing at the top, and can't figure out how to do it. If I inspect chart.chart.options the title option has the text set, and the display flag is set to true.

Here are the options that are on the actual chart.

options: {
        title: { display: true, text: 'Open Events and Registrations' },
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }

Any help is greatly appreciated!

CodePudding user response:

You will need to comment out chart.clear() and title should work.

  • Related