[Chartjs]-Remove Canvas then add new Canvas in same spot

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

Leave a comment