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

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

问题描述

我使用 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

最终为我解决的问题是:删除 元素,然后将新的 重新附加到父容器

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天全站免登陆