动画完成后,我使用 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 文档,但没有找到任何其他仅在图表构建后才会触发的选项。那么有人知道如何区分图表的悬停动画和“构建”动画吗?
将动画选项/对象替换为以下内容:
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
对象)
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();
}
}
}
});
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';
}
},
}
});
我发现 onComplete 是为了响应多个事件而触发的,包括 mouseOver(鼠标移动)和图表大小调整(当窗口大小调整时)。
为了过滤
仅“图表已初始化”的报告,我测试了事件的“初始”属性:
options: {
animation: {
onComplete: function(e) {
if ( Object.hasOwn(e, 'initial') ) {
if ( e.initial ) {
chartReady();
}
}
}
},
(“chartReady()”(当然)是我自己的用于加载后活动的外部函数。)此方法避免删除 onComplete 处理程序。 因此,在将其他数据集加载到同一图表中时,它允许额外的通知和处理。