Delete the canvas, then add a new canvas at the same location

I have the following HTML canvas:

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


With one click of a button, I want to delete canvas # graph1 and replace it with a new (chartjs) canvas. So I tried the following code:

dayButton.addEventListener("click", function(){    
  var canvas = $("#graph1").get(0);
  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);


This allows the Canvas to be removed correctly, but I'm having a hard time trying to add a new child (with the correct context and in the same place as the removed child) back to the DOM.


source to share

2 answers

You can insert the canvas after the old one and then delete the old one. The new one will have its own 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.
        return newContext;

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





While Alfonso is technically correct, I would question the effectiveness of this approach. Deleting and adding a new canvas will add overhead and potentially cause unnecessary flickering. It's good practice to get used to reusing DOM elements as much as possible.

I would highly recommend cleaning up the old canvas and reusing it. Reassign it if necessary id

to prevent other code from overwriting the new diagram.

Clearing the canvas can be done quite easily:

How to clear the canvas for redrawing