Canvas does not redraw on page reload


#1

I am using canvas to draw chartjs onto the page and that works as it should,
until user leaves the page and returns then the canvas is not showing.

  private ngAfterViewInit() {
     // if (ctx) ctx.destroy();
      let canvas: any = document.getElementById("myChart");
      let ctx = canvas.getContext("2d");
      ctx.canvas.width = 350;
      ctx.canvas.height = 300;

      var plot = new ChartJs(ctx, {
         type: 'line',
         data: {
             labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
             datasets: [{
                 label: 'Avg',
                 data: [8,7,5,6,3,2,4,5,7],
                 backgroundColor: [
                     'rgba(25,229,22,0.2)',
                 ],
                 borderColor: [
                     'rgba(25,229,22,1)',
                 ],
                 borderWidth: 1
             }

           ]
         },
         options: {
     responsive: false,
             scales: {
                 yAxes: [{
                     stacked: true
                 }]
             }
         }
       }); 
}

tried to test if canvas exist and then destroy it on every launch of ngAfterViewInit but that didn’t work because at that point it’s not even declared.

any ideas?


#2

Found the solution in this post

basicly canvas needs to be called using elementref like so:

@ViewChild('myChart') canvas:ElementRef;

and then everything works fine.