Chartjs-Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID 'idpService' can be reused

0👍

Finally I found an answer.

I needed to initialize the ctx this way:

  let ctx: CanvasRenderingContext2D = canvas.getContext("2d")!; // <--

Now I am able to display all the charts in parallel.

1👍

If you don’t want to see the charts in parallel you can simply destroy the current/topmost chart:

(this.charts[this.charts.length - 1] as Chart|undefined)?.destroy();

this.charts.push(new Chart( ......

If you are willing to destroy the chart object, then it makes little sense to keep all charts in an array, it would suffice to keep only the current chart object.

Also, in this case, of sequential charts, it is almost always possible and simpler to just change the data and options of the current chart and call its .update() method to display the next one, so you don’t destroy and recreate it.

Another option is to create a new canvas for each chart, that would allow the charts to be displayed in parallel. A simplified version would be

const serviceCanvas = document.getElementById('serviceChart') as HTMLCanvas;
if(this.charts.length > 0){
   this.canvas = document.createElement('canvas');
   serviceCanvas.parentNode!.appendChild(this.canvas);
}
else{
    this.canvas = serviceCanvas;
}

Leave a comment