Adam Jones Adam Jones - 1 year ago 67
Javascript Question

How do clear a chart from a canvas so that hover events cannot be triggered?

I'm using Chartjs to display a Line Chart and this works fine:

// get line chart canvas
var targetCanvas = document.getElementById('chartCanvas').getContext('2d');

// draw line chart
var chart = new Chart(targetCanvas).Line(chartData);

But the problem occurs when I try to change the data for the Chart. I update the graph by creating a new instance of a Chart with the new data points, and thus reinitializing the canvas.

This works fine. However, when I hover over the new chart, if I happen to go over specific locations corresponding to points displayed on the old chart, the hover/label is still triggered and suddenly the old chart is visible. It remains visible while my mouse is at this location and disappears when move off that point. I don't want the old chart to display. I want to remove it completely.

I've tried to clear both the canvas and the existing chart before loading the new one. Like:

targetCanvas.clearRect(0,0, targetCanvas.canvas.width, targetCanvas.canvas.height);



But none of these have worked so far. Any ideas about how I can stop this from happening?

Answer Source

I had huge problems with this

First I tried .clear() then I tried .destroy() and I tried setting my chart reference to null

What finally fixed the issue for me: deleting the <canvas> element and then reappending a new <canvas> to the parent container

My specific code (obviously there's a million ways to do this):

var resetCanvas = function(){
  $('#results-graph').remove(); // this is my <canvas> element
  $('#graph-container').append('<canvas id="results-graph"><canvas>');
  canvas = document.querySelector('#results-graph');
  ctx = canvas.getContext('2d');
  ctx.canvas.width = $('#graph').width(); // resize to parent width
  ctx.canvas.height = $('#graph').height(); // resize to parent height
  var x = canvas.width/2;
  var y = canvas.height/2;
  ctx.font = '10pt Verdana';
  ctx.textAlign = 'center';
  ctx.fillText('This text is centered on the canvas', x, y);

Edit 5/1/15

You can probably also use removeEventListener("eventName", handlerFunction); to avoid DOM manipulation