score:3

Accepted answer

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

});

score: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


Related Query

More Query from same tag