2

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.

Yerok
  • 67
  • 2
  • Here's a solution to creating multiple charts https://stackoverflow.com/a/51882403/1181367 – Chris Aug 19 '18 at 17:22

1 Answers1

1

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);
...
ɢʀᴜɴᴛ
  • 32,025
  • 15
  • 116
  • 110
  • I tried your solution and unfortunately I get the exact same error. – Yerok Jul 24 '17 at 12:53
  • hm. you shouldn't. maybe you have some other issues then *(which is not described in your question)*. perhaps create a jsfiddle, that reproduces the issue. – ɢʀᴜɴᴛ Jul 24 '17 at 13:04