Chart.js直到我检查元素才绘制数据,是因为异步吗?

问题描述 投票:0回答:1

我正在从.csv文件中读取数据,并将数据输入到chart.js图形中进行渲染。请看一下我的代码。它仅在我点击显示状态按钮后检查元素时才呈现。另外,我可以修改getdata函数来更新图形的数据并重新呈现吗?

下面的JavaScript:

window.onload = function () {
    chartItCountryCases();
    chartItCountryDeaths();
    getData(state);

}


function chartItCTCases(cases, days) {
        var ctx = document.getElementById('CoronaChartCTCases').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: days,
                datasets: [{
                  label: 'Cases',
                  data: cases,
                  backgroundColor: "rgb(207,181,59)"
                }]
            },
            options: {
                title: {
                    display: true,
                    text: 'Total CoronaVirus Cases in the State'
                },
                maintainAspectRatio: false,
                responsive: true,
                  scales: {
                    xAxes: [ {
                    ticks: {
                        autoSkip: true,
                        maxTicksLimit: 12
                    },
                      display: true,
                      scaleLabel: {
                        display: true,
                        labelString: 'Days since first case in the State'
                      },
                    } ],
                    yAxes: [ {
                      display: true,
                      scaleLabel: {
                        display: true,
                        labelString: 'Total Cases in the state'
                      }
                            } ]
                        }
            }
        });

        myChart.render();
    }

    function chartItCTDeaths(deaths, days) {
        var ctx = document.getElementById('CoronaChartCTDeaths').getContext('2d');
        var myChart = new Chart(ctx, {
            type: 'bar',
            data: {
            labels: days,
            datasets: [{
              label: 'Deaths',
              data: deaths,
              backgroundColor: "rgb(207,181,59)"
            }]
          },
          options: {
                title: {
                    display: true,
                    text: 'Total CoronaVirus Deaths in the State'
                },
                responsive: true,
                maintainAspectRatio: false,
                  scales: {
                    xAxes: [ {
                    ticks: {
                        autoSkip: true,
                        maxTicksLimit: 12
                    },
                      display: true,
                      scaleLabel: {
                        display: true,
                        labelString: 'Days since first case in the State'
                      },
                    } ],
                    yAxes: [ {
                      display: true,
                      scaleLabel: {
                        display: true,
                        labelString: 'Total Deaths in the state'
                      }
                            } ]
                        }
            }
        });

        myChart.render();
    }


function getData(state) { 
        cases = [];
        deaths = [];
        days = [];
        fetch('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv')
        .then((response) => {
            return response.text(); 
        })
        .then((data) => {
            const table = data.split('\n').slice(1);
            curDay = 0;
            table.forEach((row) => { 
                const columns = row.split(','); 
                if(columns[1]==state) {
                    cases.push(columns[3]);
                    deaths.push(columns[4]);
                    days.push(curDay++);
                }   
            });
        })
        chartItCTCases(cases, days);
        chartItCTDeaths(deaths, days);
    }

下面的HTML:

<div class="col-xs-12" >
                <div style="height: 300px; width: 45%;display:inline-block;"></> 
                    <canvas id="CoronaChartCTCases"> </canvas> 
                </div>
                <div style="height: 300px; width: 45%;display:inline-block;"> 
                    <canvas id="CoronaChartCTDeaths" ></canvas>
                </div>
            </div> 
javascript html chart.js fetch
1个回答
0
投票

您的假设是正确的,问题与异步fetch()方法有关。

无需在fetch()中创建图表。一旦获取的数据以图表配置中使用的格式可用,就应创建它们。因此,正确的位置是最后一个window.onload的末尾。

fetch(...).then()

请在下面查看您的修改后的代码。

fetch('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv')
    .then(response => {
      return response.text();
    })
    .then((data) => {
      ...
      chartItCTCases(cases, days);
      chartItCTDeaths(deaths, days);
    })
window.onload = function() {
  getData('New York');
}

function chartItCTCases(cases, days) {
  var ctx = document.getElementById('CoronaChartCTCases').getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: days,
      datasets: [{
        label: 'Cases',
        data: cases,
        backgroundColor: "rgb(207,181,59)"
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Total CoronaVirus Cases in the State'
      },
      maintainAspectRatio: false,
      responsive: true,
      scales: {
        xAxes: [{
          ticks: {
            autoSkip: true,
            maxTicksLimit: 12
          },
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Days since first case in the State'
          },
        }],
        yAxes: [{
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Total Cases in the state'
          }
        }]
      }
    }
  });
}

function chartItCTDeaths(deaths, days) {
  var ctx = document.getElementById('CoronaChartCTDeaths').getContext('2d');
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: days,
      datasets: [{
        label: 'Deaths',
        data: deaths,
        backgroundColor: "rgb(207,181,59)"
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Total CoronaVirus Deaths in the State'
      },
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        xAxes: [{
          ticks: {
            autoSkip: true,
            maxTicksLimit: 12
          },
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Days since first case in the State'
          },
        }],
        yAxes: [{
          display: true,
          scaleLabel: {
            display: true,
            labelString: 'Total Deaths in the state'
          }
        }]
      }
    }
  });
}


function getData(state) {
  cases = [];
  deaths = [];
  days = [];
  fetch('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv')
    .then(response => {
      return response.text();
    })
    .then((data) => {
      const table = data.split('\n').slice(1);
      curDay = 0;
      table.forEach((row) => {
        const columns = row.split(',');
        if (columns[1] == state) {
          cases.push(columns[3]);
          deaths.push(columns[4]);
          days.push(curDay++);
        }
      });
      chartItCTCases(cases, days);
      chartItCTDeaths(deaths, days);
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.