Categories
JavaScript Answers

How to clear a chart from a canvas so that hover events cannot be triggered with Chart.js and JavaScript?

Spread the love

Sometimes, we want to clear a chart from a canvas so that hover events cannot be triggered with Chart.js and JavaScript.

In this article, we’ll look at how to clear a chart from a canvas so that hover events cannot be triggered with Chart.js and JavaScript.

How to clear a chart from a canvas so that hover events cannot be triggered with Chart.js and JavaScript?

To clear a chart from a canvas so that hover events cannot be triggered with Chart.js and JavaScript, we call destroy to destroy the chart.

For instance, we write

let myPieChart = null;

//...

const drawChart = (objChart, data) => {
  if (myPieChart !== null) {
    myPieChart.destroy();
  }
  const ctx = objChart.getContext("2d");
  myPieChart = new Chart(ctx).Pie(data, { animateScale: true });
};

to create the drawChart function that calls myPieChart.destroy if myPieChart isn’t null to clear the chart.

Then we get the objChart‘s canvas context with getContext.

And we set myPieChart to a new chart created within the ctx context.

Conclusion

To clear a chart from a canvas so that hover events cannot be triggered with Chart.js and JavaScript, we call destroy to destroy the chart.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *