我遇到了一个问题,直到我在标签按钮上点击3次,我的Chart.js图表 才出现

问题描述 投票:-6回答:1

this is my canvas

this is my js function for obtaining label valuesthis is my chart.js function

javascript html json chart.js
1个回答
0
投票

查看是否适合您:

(async function() {
  var url = "https://api.covid19india.org/data.json";
  var response = await fetch(url);
  var data = await response.json();
  var barChartData = {
    labels: data.statewise
      .filter(({
        state
      }) => state !== "Total")
      .map(({
        state
      }) => state),
    datasets: [{
      label: "Confirmed cases",
      backgroundColor: "rgba(255,99,134,0.5",
      borderWidth: 1,
      data: data.statewise
        .filter(({
          state
        }) => state !== "Total")
        .map(({
          confirmed
        }) => confirmed),
    }, ],
  };
  var lineChartData = {
    labels: data.cases_time_series.map(({
      date
    }) => date),
    datasets: [{
        fill: false,
        label: "Confirmed cases",
        backgroundColor: "rgba(255,99,134,0.5",
        borderWidth: 1,
        data: data.cases_time_series.map(
          ({
            totalconfirmed
          }) => totalconfirmed
        ),
      },
      {
        fill: false,
        label: "Deceased",
        backgroundColor: "rgba(99,255,134,0.5",
        borderWidth: 1,
        data: data.cases_time_series.map(
          ({
            totaldeceased
          }) => totaldeceased
        ),
      },
    ],
  };
  var ctx = document.getElementById("canvas").getContext("2d");
  var ctx1 = document.getElementById("canvas1").getContext("2d");
  window.myBar = new Chart(ctx, {
    type: "bar",
    data: barChartData,
    options: {
      responsive: true,
      legend: {
        position: "top",
      },
      title: {
        display: true,
        text: "States with most no. of cases",
      },
    },
  });
  window.myLine = new Chart(ctx1, {
    type: "line",
    data: lineChartData,
    options: {
      responsive: true,
      legend: {
        position: "top",
      },
      title: {
        display: true,
        text: "Number of cases/deceased over time",
      },
    },
  });
})();
canvas {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>COVID-19 in India</title>
</head>

<body>
  <div id="container" style="width: 75%;">
    <p>
      <canvas id="canvas"></canvas>
    </p>
    <p>
      <canvas id="canvas1"></canvas>
    </p>
  </div>
</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.