Chart.js 动画:悬停时触发 onComplete 事件

问题描述 投票:0回答:4

动画完成后,我使用 onComplete 回调加载图表的图像导出。 我的问题是,每次您将鼠标悬停在图表上时,都会执行 onComplete 回调,这会极大地减慢页面速度。

这是我的图表代码:

this.chart = new Chart(this.$chart.getContext("2d"), {
        type: 'doughnut',
        data: data,
        options: {
            tooltips: {
                enabled: false
            },
            animation: {
                onComplete: (e) => {
                    console.log(e);
                    this.initExport();
                }
            }
        }
    });

我检查了 Chart.js 文档,但没有找到任何其他仅在图表构建后才会触发的选项。那么有人知道如何区分图表的悬停动画和“构建”动画吗?

javascript events chart.js
4个回答
7
投票

将动画选项/对象替换为以下内容:

animation: {
   onComplete(e) => {
      this.options.animation.onComplete = null; //disable after first render
      console.log(e);
      this.initExport();
   }
}

基本上,您需要通过将

chart.options.animation.onComplete
属性设置为
null
来禁用 onComplete 功能。这将使 onComplete 函数仅在第一次渲染图表后运行,并防止它在图表悬停时触发。

提示:不要对对象方法使用箭头函数。 (this

 将始终引用 
window
 对象)


2
投票
试试这个。看来您错过了函数关键字 oncomplete:

this.chart = new Chart(this.$chart.getContext("2d"), { type: 'doughnut', data: data, options: { tooltips: { enabled: false }, animation: { onComplete: function(e) { console.log(e); this.initExport(); } } } });
    

0
投票
我有同样的问题,但以不同的方式解决(放置选项:hover:onHover)。 示例:

var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: labels, ..... (other attributes) }, options: { onClick: handleClick, animation: { onComplete: function () { .... (things the onComplete do) } }, hover: { onHover:function(event, chart) { if (chart.length > 0) event.target.style.cursor = 'pointer'; } }, } });
    

0
投票
正在使用4.4.3版本,所以我不知道早期版本。

我发现 onComplete 是为了响应多个事件而触发的,包括 mouseOver(鼠标移动)和图表大小调整(当窗口大小调整时)。

为了过滤

“图表已初始化”的报告,我测试了事件的“初始”属性:

options: { animation: { onComplete: function(e) { if ( Object.hasOwn(e, 'initial') ) { if ( e.initial ) { chartReady(); } } } },
(“chartReady()”(当然)是我自己的用于加载后活动的外部函数。)

此方法避免删除 onComplete 处理程序。 因此,在将其他数据集加载到同一图表中时,它允许额外的通知和处理。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.