高图:多次替换对象时,xxx.animate无法正常工作

时间:2018-12-31 21:35:32

标签: javascript highcharts

当我多次单击按钮时,以下代码无法正常工作。我发现临时解决方案是调用chart.destroy()chart = Highcharts.chart(...)重置内部状态。但是我想知道正确的解决方案,因为这只是一个临时措施,无法解决问题的实际原因。请任何人可以帮助我吗?

var chart = Highcharts.chart('container', options);

var update = function () {
  var points = chart.series[0].points;
  chart.series[0].setData([points[0].y, points[1].y + 200]);
};

var rotate = function () {
  var points = chart.series[0].points,
      ticks = chart.xAxis[0].ticks;

  var sortedPoints = points.slice();
  sortedPoints.sort(function(a,b){
    return b.y - a.y;
  });

  points.forEach(function(point, i){
    sortedPoints.forEach(function(sPoint, j){
      if (point === sPoint){

        points[i].graphic.animate({
          x: points[j].shapeArgs.x
        });

        points[i].dataLabel.animate({
          y: points[j].dataLabel.y
        });

        ticks[i].label.animate({
          y: ticks[j].label.xy.y
        });
      }
    });
  });
};

document.getElementById("button").addEventListener("click", function() {
    update();
    rotate();
}, false);

实时演示:https://jsfiddle.net/Shinohara/dscvwrxu/22/

2 个答案:

答案 0 :(得分:1)

您不需要重置内部状态。您可以中继当前值和初始值:

var rotate = function() {
    var points = chart.series[0].points,
        index,
        ticks = chart.xAxis[0].ticks;

    var sortedPoints = points.slice();
    sortedPoints.sort(function(a, b) {
        return b.y - a.y;
    });

    points.forEach(function(point, i) {
        sortedPoints.forEach(function(sPoint, j) {
            if (point === sPoint) {
                index = j;

                if (points[i].animated) {
                    points[i].animated = false;

                    j = i;
                } else {
                    points[i].animated = true;
                }

                points[i].graphic.animate({
                    x: points[j].shapeArgs.x
                });

                points[i].dataLabel.animate({
                    y: points[index].dataLabel.y
                });

                ticks[i].label.animate({
                    y: ticks[j].label.xy.y
                });
            }
        });
    });
};

实时演示:https://jsfiddle.net/BlackLabel/jfd0vuy8/

答案 1 :(得分:0)

@ppotaczek当我多次单击按钮时,您的现场演示将无限旋转条形图。在这种情况下,我想要的是仅第一次旋转条的代码。以下是我的意图。

State1:    Cat1=1000, Cat2=900  # Current rank is 1st:Cat1 and 2nd:Cat2
Interval1: Cat2+=200 and rotate bars between state1 and state2
State2:    Cat1=1000, Cat2=1100 # Current rank is 1st:Cat2 and 2nd:Cat1
Interval2: Cat2+=200 and don't rotate bars between state2 and state3
State3:    Cat1=1000, Cat2=1300 # Current rank is 1st:Cat2 and 2nd:Cat1

我认为您的现场演示在状态2和状态3之间旋转条形的原因是update()也在旋转条形。

// This function unintentionally rotates bars for the second time.
var update = function() {
    var points = chart.series[0].points;
    chart.series[0].setData([points[0].y, points[1].y + 200]);
};

我想把条形从大到小。而且我不想在等级不变的情况下旋转小节。你有什么好的解决方案吗?