简体   繁体   中英

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.

在此处输入图片说明

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

Thanks for your help.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM