Chartjs-Chartjs removing/redrawing canvas, graph not responsive

1👍

it’s important to note that .destroy() or .clear() methods dont fit my
needs!

I think there’s something wrong going on here. The underlying problem here is that you are not destroying the chart you created first i.e. testChart. Simply removing the node does not clean it up completely.


Chart.js internally stores all instances of the charts created. When you resize the window, Chart.js loops through this list running a resize on each instance. In your code above, it errors out because the first instance is no longer in the DOM and the resize is never triggered for the 2nd instance testChart2

I’d strongly suggest you evaluate why you can’t do a .destroy() (this simply removes the instance from Chart.js internal list) before doing the .remove().

However, if there is some reason you can’t call a .destroy(), you can do one of the below


Option 1

Write your own window resize handler that triggers resize for the chart instances you want, like so

Chart.helpers.addEvent(window, "resize", (function () {
    var timeout;
    return function () {
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            myLineChart1.resize(myLineChart1.render, true);
        }, 50);
    };
})());

Option 2

Rewrite the getMaximumWidth function in the Chart.js library to add a try catch block, like so (just search for the first line to locate the block)

getMaximumWidth = helpers.getMaximumWidth = function (domNode) {
    try {
        var container = domNode.parentNode;
        // TODO = check cross browser stuff with this.
        return container.clientWidth;
    }
    catch (err)
    {}
},

Option 3

Remove the responsive option for the chart before removing it’s node, like so

myLineChart.options.responsive = false;
$("#testLine").remove();

While this doesn’t remove the unnecessary reference from the Chart.js internal list, it prevents Chart.js from triggering an (unnecessary) error causing resize for an instance that doesn’t exist in the DOM.


Here’s Option 3 in action

Fiddle – https://jsfiddle.net/0vfqw61q/

Leave a comment