[Chartjs]-Chart.js canvas, how can I swap data without the previous data affecting my hover events?

2👍

There is an option to clear a chart by .clear() method. This will clear the existing chart. There is also an option .destroy() to destroy the chart.

//This would destroy the chart.
    var mychart = new Chart(xyaz, myNinjaConfig);
    mychart.destroy();


//This would clear. the chart.
    const mychart = new Chart (xyaz, myNinjaConfig);
    mychart.clear();

1👍

You could change your options to only listen for the click event:

    options: {
        events: ['click'],
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
    }

This will only change the display when you click within it.

0👍

I couldn’t access any methods by declaring myChart as a var or const. In the end I found that by declaring

this.myChartInstance = new Chart(ctx, { ... //WORKS!!
var myChartInstance = new Chart(ctx, { ... //doesnt work
const myChartInstance = new Chart(ctx, { ... //doesnt work

I could now call destroy method from the console.

Adding a conditional check before re-initializing my data, works great!! I can hover over my graph and swap data without any conflict. Solution:

if (this.myChartInstance) {
    this.myChartInstance.destroy();
}
this.myChartInstance = new Chart(ctx, { ...

Leave a comment