我有以下代码利用ChartJS库。
/*assume the tags in the right place */
<canvas id="graph1" width="300" height="300"></canvas>
var ctx = $("#graph1").get(0).getContext("2d");
var myChart = new Chart(ctx).Line(graph1Generator("day"));
...一切正常,但在添加以下事件处理程序以清除并重新绘制具有不同数据的相同图表后,会出现故障。
weekButton.addEventListener("click", function(){
ctx.clearRect (0, 0, 300, 300);
ctx.canvas.width = 300;
ctx.canvas.height = 300;
myChart = new Chart(ctx).Line(graph1Generator("week"));
这段代码使用新数据成功地重绘了图表,但是当我将鼠标悬停在它上面时,它会做一些非常奇怪的&#34;闪回&#34;它应该清除的旧图表。这让我相信它并没有清除旧的。
答案 0 :(得分:8)
Here is an update to your fiddle.主要更改(除了修复功能名称拼写错误)是添加
myChart.destroy();
在之类的行之前
myChart = new Chart(ctx).Line(...);
.destroy()
方法摆脱了事件处理程序注册等,所以你不应该看到那些奇怪的&#34; ghost图表&#34;当你将鼠标悬停在图形上时。