【问题标题】:How to remove old chart and append new chart to div using chartjs如何使用chartjs删除旧图表并将新图表附加到div
【发布时间】:2022-02-13 00:30:52
【问题描述】:

当用户单击按钮检索新图表时,我需要删除旧图表。我知道在创建新图表之前需要销毁图表,但图表不是全局创建的,它们不能用我现在拥有的代码销毁。有什么解决方法吗? 当我单击另一个按钮以显示图表时,它不会显示,因为之前的图表/画布仍然存在

<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-12 p-0">
        <div class="jumbotron min-vh-100 text-center m-0 d-flex flex-column">
          <h1 class="display-1" style="margin-top: 10px">Sentiment</h1>
          <form v-on:submit.prevent="generateSentiment().then(getSentiment)">
            <p style="margin-top: 30px">
              <input
                :disabled="isDisabled"
                v-model="video_ID"
                type="text"
                class="form-control input-lg mx-auto"
                id="youtube-url"
                placeholder="youtube addess"
                style="width: 15%"
              />
            </p>
            <p style="margin-top: 30px">
              <button class="btn btn-primary btn-lg" :disabled="isDisabled" v-on:click="isHidden = !isHidden">get sentiment</button>
            </p>
            <p style="margin-top: 28px"><span>{{ sentimentComment }}</span></p>
            <p style="margin-top: 5px" v-if="!isHidden">Refresh to generate new sentiment</p>
          </form>
          <p style="margin-top: 10px"></p>
           <div class="btn-groupd">
                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden" @click="drawChart">Total Sentiment</button>
                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden" @click="drawPieChart">ML Sentiment</button>
                <button class="btn btn-secondary mr-1" role="button" v-if="!isHidden">Lexicon Sentiment</button>
          </div>
          <div id = "canvas-div">
          <canvas v-if="!isHidden" id = 'example' height = '90' width = '400' ></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import { defineComponent } from "vue";
import { Chart, registerables } from "chart.js";


export default defineComponent({
  name: "app",
  data() {
    return {
      commentSentiment: "",
      video_ID: "",
      sentimentRank: 0,
      sentimentComment: "",
      totalPositiveSent: 0,
      totalNegativeSent: 0,
      totalPosMLSen: 0,
      totalNegMLSen: 0,
      isHidden: true,
      isDisabled: false,
    };
  },
  methods: {
    generateSentiment: function() {
      this.isDisabled = true
      return axios
        .post("http://localhost:3000/api/yt", { video_ID: `${this.video_ID}` })
        .then((response) => {
          this.video_ID = response.data.video_ID;
        })
        .catch((error) => {
          window.alert(`The api returned an error: ${error}`);
        });
        
    },
    getSentiment: function() {
      return axios
        .get("http://localhost:3000/api/yt/get")
        .then((response) => {
          this.sentimentRank = response.data.sentScore.SentScore;
          this.totalPositiveSent =
            response.data.sentScore.TotalPositiveComments;
          this.totalNegativeSent =
            response.data.sentScore.TotalNegativeComments;
          this.totalPosMLSen = response.data.sentScore.PositiveMLComments
          this.totalNegMLSen = response.data.sentScore.NegativeMLComments
          // console.log(this.totalPositiveSent)
          if (this.sentimentRank == 0) {
            return;
          } else if (this.sentimentRank == 1) {
            return (this.sentimentComment = `This video has a good sentiment`);
          } else if (this.sentimentRank == -1) {
            return (this.sentimentComment = `This video has a bad sentiment`);
          }
        })
   
        .catch((error) => {
          window.alert(`The api returned an error: ${error}`);
        });
    },
    drawChart: function() {
      Chart.register(...registerables)
      let canvas = document.getElementById('example')
        let ctx = canvas.getContext('2d')
        const chrt = new Chart(ctx, {
        type: 'bar',
        data: {
        labels: ["Positive Sentiment", "Negative Sentiment"],
        datasets: [
          {
            label: "Overall Sentiment",
            backgroundColor: ["green", "red"],
            data: [this.totalPositiveSent, this.totalNegativeSent],
          },
          ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: true,
      }
      });
        chrt.render();
    },
    drawPieChart: function() {
      Chart.register(...registerables)
      let canvas = document.getElementById('example')
      let ctx = canvas.getContext('2d')
      const chrt = new Chart(ctx, {
        type: 'pie',
        data: {
        labels: ["Positive Sentiment", "Negative Sentiment"],
        datasets: [
          {
            label: "Overall ML Sentiment",
            backgroundColor: ["green", "red"],
            data: [this.totalPosMLSen, this.totalNegMLSen],
          },
          ],
      },
      options: {
        responsive: true,
        maintainAspectRatio: true,
      }
      });
        chrt.render();
    },
  },
});
</script>

【问题讨论】:

    标签: javascript html vue.js chart.js


    【解决方案1】:

    您可以使用API​​方法getChart来查看它是否存在。如果不存在则返回未定义,如果存在则返回该图表。

    所以你会得到:

    const tmpChart = Chart.getChart('canvasID');
    if (tmpChart) {
      tmpChart.destroy()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      相关资源
      最近更新 更多