Yerok
Yerok

Reputation: 67

Impossible to render multiple charts with chart.js

I'm trying to create multiple charts on a single page with Chart.js I'm dynamically creating several canvas to host those charts.

The information concerning each charts are contained into JSON objects which are contained into 'allDatas'.

Note that the datas from allDatas are correctly formatted and each one have been tested, we can correctly create a Chart without any problem with them. It's the same for the canvas, they're all correct and we can display a chart in any of them. The problem occur when I'm trying to create multiple charts.

var displayDataviz = function(){
    var datavizCanvas = document.querySelectorAll('.js-datavizCanvas');

    for(var i=0; i<datavizCanvas.length;i++){
        var canvas = datavizCanvas[i];
        var data = allDatas[i];
        data = data.replace(/&quot;/g,'\"');

        data = JSON.parse(data);
        reCreateDataviz(canvas,data);

    }
}

var reCreateDataviz = function(canvas, previousDataviz) {
    console.log(canvas);
    console.log(previousDataviz);
    var myChart = new Chart(canvas, previousDataviz);
    return myChart;
}

Here's what I obtain in the console, I logged the two objects so you can see that they're correct, and you can also see that the first chart (totally random) works fine.

enter image description here

I tried to create them manually and the same problem occurs.

Thanks for your help.

Upvotes: 2

Views: 1761

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32859

This reason why it­'s not working is because, you are storing all the chart instances to a single variable (myChart), which distorts all other chart instances, except one.

To resolve this ...

add another parameter to the reCreateDataviz function ( for instance - chartID ), which will contain an unique id for each chart :

var reCreateDataviz = function(canvas, previousDataviz, chartID) {
  ...
}

then, declare the variable, that stores the chart instance, like this :

window['myChart' + chartID] = new Chart(canvas, previousDataviz);

and finally, when calling reCreateDataviz function inside the for loop, pass i as the third argument, like so :

...
reCreateDataviz(canvas, data, i);
...

Upvotes: 1

Related Questions