3

I have the following HTML canvas':

<div id="graphs">
  <canvas id="graph1"  ></canvas>
  <canvas id="graph2" ></canvas>
  <canvas id="graph3" ></canvas>
</div>

On a click of a button, I want to remove canvas #graph1 and replace it will a new (chartjs) canvas. So I tried the following code:

dayButton.addEventListener("click", function(){    
  var canvas = $("#graph1").get(0);
  canvas.parentNode.removeChild(canvas);
  var parent = $("#graphs").get(0);
  var new_canvas = document.createElement("canvas");
  var new_ctx =new_canvas.getContext("2d");
  myChart = new Chart(new_ctx).Line(somedata);
  parent.appendChild(new_canvas); 
}

This gets the Canvas to properly remove, but I am having a hard time trying to append the new child (with the correct context and in the same spot as the removed child) back into the DOM.

ApathyBear
  • 6,991
  • 12
  • 48
  • 84

2 Answers2

3

You can insert the canvas after the old one, and then remove the old one. The new one will have its position.

dayButton.addEventListener("click", function() {

    function replaceCanvas(elem) {
        var canvas = document.createElement('canvas'),
            newContext = canvas.getContext('2d');
        // Insert the new canvas after the old one
        elem.parentNode.insertBefore(canvas, elem.nextSibling);
        // Remove old canvas. Now the new canvas has its position.
        elem.parentNode.removeChild(elem);
        return newContext;
    }

    var new_ctx = replaceCanvas(document.getElementById('graph1'));
    myChart = new Chart(new_ctx).Line(somedata);

});
0

While Alfonso is technically correct, I would question the performance of this approach. Removing and adding a new Canvas is going to add overhead and potentially cause unnecessary flicker. It is good practice to get in the habit of reusing DOM elements as much as possible.

I would highly recommend clearing the old Canvas and then reusing it. If necessary reassign its id so that other code will not overwrite your new chart.

Clearing a canvas can be accomplished quite easily:

How to clear the canvas for redrawing

Community
  • 1
  • 1
JoshJ
  • 839
  • 9
  • 22
  • I appreciate the answer, yet I have tried clearing the canvas, and using destroy. I has caused some issues. See [here](http://stackoverflow.com/questions/30063762/side-effects-from-chartjs-for-only-some-clients). – ApathyBear May 07 '15 at 05:55