最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to 'destroy' previous chart (canvas) after new one is shown | Angular 4 - Stack Overflow

programmeradmin4浏览0评论

I have a code that update the data of an Graphic after a drop down is selected. However when I select an option it looks like the new Graphic and the old Graphic stays on the same canvas at the same time.

here's my code:

funcao(){

  this.graphicService.getDatas().subscribe(datas => {
        this.datas = datas; //Gets the data from the API and put on local datas variable

        if(this.data[0].dimension == "Tech")
        {
          this.counter=0;
        }
        else if(this.data[0].dimension == "Bus"){
          this.counter=1;
        }
              this.barChartData = { //Bar graphic data
                  labels: ["Entry", "Foundation"],
                  datasets: [{
                      label: this.datas[this.counter].subdimensions[0].name,
                      backgroundColor: 'rgba(37, 230, 131,0.7)'
                      data: [
                          this.datas[this.counter].subdimensions[0].entry,
                          this.datas[this.counter].subdimensions[0].foundation
                      ]
                  }]

              };

              this.canvas = document.getElementById('myChart');
              this.ctx = this.canvas.getContext('2d');

              let myChart = new Chart(this.ctx, { // Bar graphic configs
                     type: 'bar',
                     data: this.barChartData,
                     options: {
                         scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                          }
                     }
                 });
      });
}

HTML

<select [(ngModel)]="data[0].dimension" (change)="funcao()" class="form-control">
  <option *ngFor="let data of datas" [value]="data.dimension">{{ data.dimension }}</option>
</select>

  <canvas id="myChart"></canvas>

What I want to do is the old graphic disappears and only the new one stay on screen.

I have a code that update the data of an Graphic after a drop down is selected. However when I select an option it looks like the new Graphic and the old Graphic stays on the same canvas at the same time.

here's my code:

funcao(){

  this.graphicService.getDatas().subscribe(datas => {
        this.datas = datas; //Gets the data from the API and put on local datas variable

        if(this.data[0].dimension == "Tech")
        {
          this.counter=0;
        }
        else if(this.data[0].dimension == "Bus"){
          this.counter=1;
        }
              this.barChartData = { //Bar graphic data
                  labels: ["Entry", "Foundation"],
                  datasets: [{
                      label: this.datas[this.counter].subdimensions[0].name,
                      backgroundColor: 'rgba(37, 230, 131,0.7)'
                      data: [
                          this.datas[this.counter].subdimensions[0].entry,
                          this.datas[this.counter].subdimensions[0].foundation
                      ]
                  }]

              };

              this.canvas = document.getElementById('myChart');
              this.ctx = this.canvas.getContext('2d');

              let myChart = new Chart(this.ctx, { // Bar graphic configs
                     type: 'bar',
                     data: this.barChartData,
                     options: {
                         scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero: true
                                }
                            }]
                          }
                     }
                 });
      });
}

HTML

<select [(ngModel)]="data[0].dimension" (change)="funcao()" class="form-control">
  <option *ngFor="let data of datas" [value]="data.dimension">{{ data.dimension }}</option>
</select>

  <canvas id="myChart"></canvas>

What I want to do is the old graphic disappears and only the new one stay on screen.

Share Improve this question asked Sep 27, 2017 at 18:48 GustavoGustavo 9144 gold badges13 silver badges27 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 16

Seems like you are using the ChartJS library. In that case, you can use the destroy() method to destroy any previous instance of chart.

ꜰɪʀꜱᴛ

add a property (in which the chart instance gonna be stored) in your chart component class :

public myChart: Chart

ꜱᴇᴄᴏɴᴅ

check and destroy the chart instance (if any) before creating a new one :

...
if (this.myChart) this.myChart.destroy(); //destroy prev chart instance
this.myChart = new Chart(this.ctx, {
         type: 'bar',
         data: this.barChartData,
         ...

I know this has already been solved, but I was having the same problem and this solutions didn't work, probably because I am using recent versions.

In case someone is reading this thread and is in the same situation as me, this is what worked in my case: manually removing the canvas from the DOM in the ngOnDestroy() hook.

  ngOnDestroy(){
    ( < HTMLCanvasElement > document.getElementById('myChartCanvas')).remove();
  }

The canvas api defines a clearRect method.

You can clear the canvas before creating a new chart.

this.ctx = this.canvas.getContext('2d');
this.ctx.clearRect(0, 0, 100,100);

You read the documentation here.

try destroy() method.

Keep accessible reference to your chart instance (this.myChart in my example):

this.myChart = new Chart(this.ctx, { // Bar graphic configs
  type: 'bar',
  data: this.barChartData,
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

then, when you need to destroy it, call:

// Destroys a specific chart instance
this.myChart.destroy();

here is destroy() function's code (copied from CDN):

destroy : function(){
  this.clear();
  unbindEvents(this, this.events);
  var canvas = this.chart.canvas;

  // Reset canvas height/width attributes starts a fresh with the canvas context
  canvas.width = this.chart.width;
  canvas.height = this.chart.height;

  // < IE9 doesn't support removeProperty
  if (canvas.style.removeProperty) {
    canvas.style.removeProperty('width');
    canvas.style.removeProperty('height');
  } else {
    canvas.style.removeAttribute('width');
    canvas.style.removeAttribute('height');
  }

  delete Chart.instances[this.id];
}

and clear() function:

clear = helpers.clear = function(chart){
  chart.ctx.clearRect(0,0,chart.width,chart.height);
}

so, destroy() function take care of both ChartJS and canvas APIs, and, as stated on the official site:

This must be called before the canvas is reused for a new chart

发布评论

评论列表(0)

  1. 暂无评论