chart.js load totally new data

前端 未结 20 1449
有刺的猬
有刺的猬 2020-11-28 21:12

The API for chart.js allows one to edit points of the datasets loaded into it, for example:

.update( )

Calling update() on

20条回答
  •  时光说笑
    2020-11-28 21:37

    There is a way to do this without clearing the canvas or starting over, but you have to man handle the creation of the chart so that the data is in the same format for when you update.

    Here is how I did it.

        var ctx = document.getElementById("myChart").getContext("2d");
        if (chartExists) {
            for (i=0;i<10;i++){
                myNewChart.scale.xLabels[i]=dbLabels[i]; 
                myNewChart.datasets[0].bars[i].value=dbOnAir[i];
            }
            myNewChart.update();
          }else{
              console.log('chart doesnt exist');
              myNewChart = new Chart(ctx).Bar(dataNew);
              myNewChart.removeData();
              for (i=0;i<10;i++){
                  myNewChart.addData([10],dbLabels[i]);
              }
              for (i=0;i<10;i++){      
                  myNewChart.datasets[0].bars[i].value=dbOnAir[i];
              }
              myNewChart.update();
              chartExists=true;
            }
    

    I basically scrap the data loaded in at creation, and then reform with the add data method. This means that I can then access all the points. Whenever I have tried to access the data structure that is created by the:

    Chart(ctx).Bar(dataNew);
    

    command, I can't access what I need. This means you can change all the data points, in the same way you created them, and also call update() without animating completely from scratch.

提交回复
热议问题