如何从画布中清除图表,以便不能触发悬停事件? [英] How to clear a chart from a canvas so that hover events cannot be triggered?

查看:172
本文介绍了如何从画布中清除图表,以便不能触发悬停事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Chartjs来显示折线图,效果很好:

I'm using Chartjs to display a Line Chart and this works fine:

// get line chart canvas
var targetCanvas = document.getElementById('chartCanvas').getContext('2d');

// draw line chart
var chart = new Chart(targetCanvas).Line(chartData);

但是当我尝试更改图表的数据时会出现问题。我通过创建带有新数据点的图表的新实例来更新图表,从而重新初始化画布。

But the problem occurs when I try to change the data for the Chart. I update the graph by creating a new instance of a Chart with the new data points, and thus reinitializing the canvas.

这很好。但是,当我将鼠标悬停在新图表上时,如果我碰巧查看与旧图表上显示的点相对应的特定位置,则悬停/标签仍然被触发,突然显示旧图表。它保持可见,而我的鼠标在这个位置,消失时移动该点。我不想显示旧的图表。我想要完全删除它。

This works fine. However, when I hover over the new chart, if I happen to go over specific locations corresponding to points displayed on the old chart, the hover/label is still triggered and suddenly the old chart is visible. It remains visible while my mouse is at this location and disappears when move off that point. I don't want the old chart to display. I want to remove it completely.

我已经尝试清除画布和现有的图表,然后再加载新的。喜欢:

I've tried to clear both the canvas and the existing chart before loading the new one. Like:

targetCanvas.clearRect(0,0, targetCanvas.canvas.width, targetCanvas.canvas.height);

chart.clear();

但是这些都没有工作。

But none of these have worked so far. Any ideas about how I can stop this from happening?

推荐答案

我对此有很大的问题

首先我尝试了 .clear()然后我尝试了 .destroy()将我的图表引用设置为null

First I tried .clear() then I tried .destroy() and I tried setting my chart reference to null

最终解决了我的问题:删除< canvas> 元素然后将新的< canvas> 重新添加到父容器中

What finally fixed the issue for me: deleting the <canvas> element and then reappending a new <canvas> to the parent container

我的具体代码(显然有一百万种方法可以做到这一点):

My specific code (obviously there's a million ways to do this):

var resetCanvas = function(){
  $('#results-graph').remove(); // this is my <canvas> element
  $('#graph-container').append('<canvas id="results-graph"><canvas>');
  canvas = document.querySelector('#results-graph');
  ctx = canvas.getContext('2d');
  ctx.canvas.width = $('#graph').width(); // resize to parent width
  ctx.canvas.height = $('#graph').height(); // resize to parent height
  var x = canvas.width/2;
  var y = canvas.height/2;
  ctx.font = '10pt Verdana';
  ctx.textAlign = 'center';
  ctx.fillText('This text is centered on the canvas', x, y);
};

这篇关于如何从画布中清除图表,以便不能触发悬停事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆