Javascript 如何使用chart.js删除图表实例

Javascript 如何使用chart.js删除图表实例,javascript,chart.js,Javascript,Chart.js,我的网页加载并自动创建一个图表,其中包含从我编写的API中提取的数据。 我还得到了一个HTML输入,可以让我选择月份。我在输入中添加了一个事件监听器,该监听器触发一个函数,根据我选择的月份绘制一个新图表(它也使用这些新参数调用api) 它看起来很有效,但进一步检查后,我意识到上一张图表在新图表的后面 有没有办法删除旧图表 <div class="chart_div" style="max-height: 400px; max-width: 800px; mar

我的网页加载并自动创建一个图表,其中包含从我编写的API中提取的数据。 我还得到了一个HTML输入,可以让我选择月份。我在输入中添加了一个事件监听器,该监听器触发一个函数,根据我选择的月份绘制一个新图表(它也使用这些新参数调用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>

开始月份:
var canvas=document.getElementById(“myChart”);
const context=canvas.getContext(“2d”);
var monthSelector=document.getElementById(“monthSelector”);
//月滑块的事件侦听器
monthSelector.addEventListener(“输入”,函数(){
所选日期=月选择值+“-01”;
图纸(所选日期);
});
var today=月Selector.value+“-01”;
//加载页面时绘制图表
绘图图(今日);
功能图(日期){
x_标签=[];
数据集=[];
数据集医疗评分=[];
clearRect(0,0,canvas.width,canvas.height);
变量url_=
"http://127.0.0.1:8000/api/get-每日划痕计数/“+日期+”/”;
var url_医学_分数=
"http://127.0.0.1:8000/api/get-每日医疗评分/“+日期+”/”;
//根据所选月份的日期获取x标签
var date\U VAL=拆分日期(“-”);
var num_days=getDaysInMonth(日期[1],日期[0]);
控制台日志(天数);
for(var i=1;i res.json())
.then(功能(数据){
var=数据;
var-dateIndex=0;
var scratchesIndex=0;
而(划痕指数<划痕长度){
var scratchDates=scratchs[ScratchsIndex].date.split(“-”;//将日期拆分为列表[“YYYY”、“MM”、“DD”]
//如果日期相等,则推送总计并增加两个索引
if(scratchDates[2]==x_标签[dateIndex]){
数据集\u scratches.push(scratches[scratchesIndex].total);
dateIndex+=1;
划痕指数+=1;
//如果日期不相等,则按0并仅增加日期索引
}否则{
数据集推送(0);
dateIndex+=1;
}
}
console.log(数据集);
}),
获取(url\u医学\u分数)
.然后((res)=>res.json())
.then(功能(数据){
var medicalScores=数据;
var-dateIndex=0;
var评分指数=0;
while(得分指数

我真正想做的是在再次调用api之前删除现有图表?任何帮助都将不胜感激。

调用图表对象的销毁方法

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