ApathyBear
ApathyBear

Reputation: 9595

Remove Canvas then add new Canvas in same spot

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.

Upvotes: 3

Views: 5691

Answers (2)

JoshuaJ
JoshuaJ

Reputation: 979

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

Upvotes: 0

user4698813
user4698813

Reputation:

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);

});

Upvotes: 3

Related Questions