簡體   English   中英

如何使用 chart.js 刪除圖表實例

[英]How can I delete an instance of a chart using chart.js

我的 web 頁面加載並自動創建一個圖表,其中包含從我寫的 API 中提取的數據。 我還有一個 HTML 輸入,允許我在一個月內輸入 select。 我已經向該輸入添加了一個事件偵聽器,它會觸發 function 以根據我選擇的月份繪制新圖表(它也會使用這些新參數調用 api)。

看起來它有效,但在進一步檢查時,我意識到以前的圖表落后於新圖表。

有什么辦法可以刪除舊圖表嗎?

<div class="chart_div" style="max-height: 400px; max-width: 800px; margin: 5px">
  <label for="monthSelector">Start month:</label>

  <input
    type="month"
    id="monthSelector"
    name="start"
    min="{{min_date}}"
    max="{{today_date}}"
    value="{{today_date}}"
  />
  <canvas id="myChart" width="400" height="400"> </canvas>
</div>

<script>
  var canvas = document.getElementById("myChart");
  const context = canvas.getContext("2d");
  var monthSelector = document.getElementById("monthSelector");
  //  event listener for month slider
  monthSelector.addEventListener("input", function () {
    selected_date = monthSelector.value + "-01";
    drawChart(selected_date);
  });
  var today = monthSelector.value + "-01";

  //  Draw chart upon loading page
  drawChart(today);

  function drawChart(date) {
    x_labels = [];
    data_set_scratches = [];
    data_set_medical_scores = [];
    context.clearRect(0, 0, canvas.width, canvas.height);
    var url_scratches =
      "http://127.0.0.1:8000/api/get-daily-scratch-count/" + date + "/";
    var url_medical_scores =
      "http://127.0.0.1:8000/api/get-daily-medical-score/" + date + "/";

    // get x label based on dates of selected month
    var date_vals = date.split("-");
    var num_days = getDaysInMonth(date_vals[1], date_vals[0]);
    console.log(num_days);
    for (var i = 1; i <= num_days; i++) {
      var num = minTwoDigits(i);
      x_labels.push(num);
    }

    //  call api to fetch the data
    Promise.all([
      fetch(url_scratches)
        .then((res) => res.json())
        .then(function (data) {
          var scratches = data;
          var dateIndex = 0;
          var scratchesIndex = 0;
          while (scratchesIndex < scratches.length) {
            var scratchDates = scratches[scratchesIndex].date.split("-"); //  Splits date into list ["YYYY", "MM", "DD"]
            //  if dates are equal, push total and increase both index
            if (scratchDates[2] == x_labels[dateIndex]) {
              data_set_scratches.push(scratches[scratchesIndex].total);
              dateIndex += 1;
              scratchesIndex += 1;
              //  if dates are not equal, push 0 and increase only date index
            } else {
              data_set_scratches.push(0);
              dateIndex += 1;
            }
          }
          console.log(data_set_scratches);
        }),
      fetch(url_medical_scores)
        .then((res) => res.json())
        .then(function (data) {
          var medicalScores = data;
          var dateIndex = 0;
          var scoreIndex = 0;
          while (scoreIndex < medicalScores.length) {
            var scoreDates = medicalScores[scoreIndex].date.split("-"); //  Splits date into list ["YYYY", "MM", "DD"]
            // if dates are equal, push score then increase both index
            if (scoreDates[2] == x_labels[dateIndex]) {
              data_set_medical_scores.push(medicalScores[scoreIndex].score);
              dateIndex += 1;
              scoreIndex += 1;
              //  if dates are not equal, push 0 and increase only date index
            } else {
              data_set_medical_scores.push(0);
              dateIndex += 1;
            }
          }
          console.log(data_set_medical_scores);
        }),
    ]).then(function () {
      //  Creat chart from api Data
      let chartTest = new Chart(myChart, {
        type: "line",
        data: {
          labels: x_labels,
          datasets: [
            {
              label: "Scratch Total",
              fill: false,
              data: data_set_scratches,
              borderColor: "green",
              borderWidth: 1,
              lineTension: 0,
              backgroundColor: "red",
              pointBackgroundColor: "red",
              pointBorderColor: "red",
              pointHoverBackgroundColor: "red",
              pointHoverBorderColor: "red",
            },
            {
              data: data_set_medical_scores,
              label: "Medical Score",
              fill: false,
              borderColor: "orange",
              borderWidth: 1,
              lineTension: 0,
              backgroundColor: "#e755ba",
              pointBackgroundColor: "#55bae7",
              pointBorderColor: "#55bae7",
              pointHoverBackgroundColor: "#55bae7",
              pointHoverBorderColor: "#55bae7",
            },
          ],
        },
        options: {
          title: {
            display: true,
            text: "Daily Scratches/Medical Scores",
          },
          scales: {
            yAxes: [
              {
                ticks: {
                  beginAtZero: true,
                },
              },
            ],
            xAxis: [
              {
                ticks: {
                  stepSize: 1,
                  autoSkip: false,
                },
              },
            ],
          },
        },
      });
    });
  }

  // function to get num of days in month
  function getDaysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
  }

  function minTwoDigits(n) {
    return (n < 10 ? "0" : "") + n;
  }
</script>

我真正想做的是在再次調用 api 之前刪除現有圖表? 任何幫助將不勝感激。

調用圖表的 destroy 方法 object

.destroy()
Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js. This must be called before the canvas is reused for a new chart.

// Destroys a specific chart instance
myLineChart.destroy();

https://www.chartjs.org/docs/latest/developers/api.html?h=destroy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM