图表 js 角度错误:画布已在使用中。ID 为"0"的图表必须先销毁,然后才能重复使用画布。修复?



所以基本上,在div click (jquery)上,我有一个有图表的bootstrap模式弹出。图表工作得很好,渲染也很完美,但当我单击另一个div时,问题就出现了。

我的HTML

<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="card">
<div class="text-right cross"> hello<i class="fa fa-times"></i> </div>
<div id="chartDiv" *ngIf="chart"><canvas #chart>{{  chart  }}</canvas></div>   
</div>
</div>
</div>

在一个单独的注意,我使用Chart.register(…registerables)在我的构造函数。下面是我的TS(只是相关代码):

import { Chart, registerables } from 'chart.js';
export class HomeComponent implements OnInit{
@ViewChild('chart') canvas: ElementRef;
chart: any = [];
ngOnInit(): void {   
$('#myModal').on('hide.bs.modal', function () {
$(".canvas").remove(); 
})
$('#myModal').on('show.bs.modal', function () {
$("div.chart").append('<canvas #chart>{{chart}}</canvas>');
$('#chart').trigger('focus')
})
}
divClick()
{
$('#myModal').modal('show'); 
this.chart = this.getChartData()
}
getChartData(): Chart {
this.chart = new Chart(this.canvas.nativeElement.getContext('2d'), {data})
//please don't worry about data its coming from api and it works fine
return this.chart
}
}

这只是非常高的水平,但我很高兴包括任何其他需要的代码。我研究了很多文章和修复这个错误的方法,但没有找到任何方法。如果你能给我指出一个使用Angular实现Chart js的资源,那就很有帮助了。此外,我还尝试了"摧毁"。函数。图表,但这也不行。除了暴露画布,还有其他方法可以使用这个吗?只是不知道我哪里做错了。我甚至尝试通过jquery(在onInit)删除和重新添加画布类,但这也不起作用。(Chartjs v3.7.0)

你做的每件事都是对的,你离成功很近了。我认为没有必要在这个图表中存储任何东西。简单地返回并渲染。要修复您的多实例错误,只需在渲染前添加一个图表存在检查。

divClick()
{
var chartExist = Chart.getChart("myChart"); // <canvas> id
if (chartExist != undefined)  
chartExist.destroy(); 
$('#myModal').modal('show'); 
this.getChartData()
}
getChartData(): any {
return new Chart(this.canvas.nativeElement.getContext('2d'), {data})

}

在你的HTML中,只需添加id为图表

<canvas id="myChart" #chart>{{  chart  }}</canvas>

相关内容

最新更新