Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJs line chart repaint glitch while hovering over

I have the following code leveraging the ChartJS library.

/*assume the tags in the right place */

<canvas id="graph1" width="300" height="300"></canvas>

var ctx = $("#graph1").get(0).getContext("2d");
var myChart = new Chart(ctx).Line(graph1Generator("day"));

... everything works fine, but after adding the following event handler to clear and repaint the same chart with different data, a glitch occurs.

weekButton.addEventListener("click", function(){
    ctx.clearRect (0, 0, 300, 300);
    ctx.canvas.width = 300;
    ctx.canvas.height = 300;
    myChart = new Chart(ctx).Line(graph1Generator("week"));

This code does successfully redraw the chart with the new data, but when I hover over it, it does some very strange "flashbacks" to the old chart that it was supposed to clear. This makes me believe that it didn't clear the old one.

like image 848
ApathyBear Avatar asked May 05 '15 16:05

ApathyBear


People also ask

How do I make a line chart responsive?

To make chart responsive just set responsive key to true inside lineChartOptions. Also, remember to remove :width and :height properties from the element and make the wrapper element responsive via css/scss.

How do you change colors in Chartjs?

With ChartJS 3, you can change the color of the labels by setting the scales. x. ticks. color and scales.

What is Maintainaspectratio?

If you select the Maintain Aspect Ratio check box, the embedded Mimic will retain its original proportions. This means that when you resize the embedded Mimic, its width and height will maintain their relationship, for example, if you reduce the height, the width will also reduce automatically.


1 Answers

Here is an update to your fiddle. The primary change (other than fixing the function name typo) is to add

myChart.destroy();

before lines like

myChart = new Chart(ctx).Line(...);

The .destroy() method gets rid of the event handler registrations etc, so you shouldn't see those weird "ghost charts" when you mouse over the graphics.

like image 151
Pointy Avatar answered Sep 20 '22 08:09

Pointy