仅在悬停时触发Chart.js动画吗?

时间:2019-08-06 07:48:08

标签: javascript chart.js

我试图在animation.onComplete中执行一个新的动画。效果是第二个动画仅在图表悬停时开始。 是否可以让它独立于悬停启动?

Chart.plugins.register({
   beforeUpdate: function (chart) {
       if (chart.options.sort) {

           let dataArray = chart.data.datasets[0].data;
           let dataIndexes = dataArray.map((d, i) => i);
           dataIndexes.sort((a, b) => {
                return dataArray[b] - dataArray[a]; 
           });

           dataArray.sort((a, b) => b - a); 

           let meta = chart.getDatasetMeta(0);
           let newMeta = [];
           let labels = chart.data.labels;
           let newLabels = [];
           let newColors = [];

           meta.data.forEach((bar, i) => {
                let newIndex = dataIndexes.indexOf(i);
                newMeta[newIndex] = bar;
                newLabels[newIndex] = chart.data.labels[i];
                newColors[newIndex] = chart.data.datasets[0].backgroundColor[i];
           });

           meta.data = newMeta;
           chart.data.labels = newLabels;
           chart.data.datasets[0].backgroundColor = newColors;

         }
     }                  
});

chart = JSON.parse(url); //url is a text loaded from DB containing chart defaults

chart.options.animation = new Object();
chart.options.animation.onComplete = function (animation) {
    this.options.animation.onComplete = null; //disable after first render
    this.options.sort = true;
    this.update();
    this.options.sort = false; 
}

var ctx = $("#myChart");
var myChart = new Chart(ctx, chart);

2 个答案:

答案 0 :(得分:0)

最后,我使用Window setTimeout()方法解决了..

 var ctx = $("#myChart");
var myChart = new Chart(ctx, chart);

function AlertFunc (chart) {
    chart.options.sort = true;
    chart.update();
    chart.options.sort = false;  
}

window.setTimeout(function () { AlertFunc(myChart); }, 2000)

答案 1 :(得分:0)

我遇到了同样的问题。通过将 animation.duration0 更改为 0.1 来修复它:

chart.options.animation = {      
   duration: 0.1,
   ...
}