2

我正在使用 WebGL 的 Globe API 及其旋转动画功能,但我希望用户能够通过双击地球来停止和重新启动动画。

目前我有以下运行onload的动画代码:

function performAnimation() {
      requestAnimationFrame(function animate(now) {
        if (animated) {
          var c = earth.getPosition();
          var elapsed = before? now - before: 0;
          before = now;
          earth.setCenter([c[0], c[1] + 0.1*(elapsed/30)]);
          requestAnimationFrame(animate);
        }


      });
    }

以下代码在双击时停止并重新启动动画:

performAnimation()
    var animated = true;
    var touchtime = 0;

    $('#globe').on('click', function() {
      if(touchtime == 0) {
        touchtime = new Date().getTime();
      } else {
        if(((new Date().getTime()) - touchtime) < 200) {
          if (animated) {
            animated = false;
          } else {
            animated = true;
            performAnimation()
          }
          console.log(animated);
          //alert(animated);

          touchtime = 0;
        } else {
          touchtime = 0;
        }
      } 
    });

停止和停止在双击时起作用。问题是当动画停止时,时间仍然过去,当动画重新开始时,地球的中心会立即移动到它没有停止时的位置。

如何确保当地球动画重新启动时,它从当前中心而不是假设中心重新启动?

4

1 回答 1

1

所以我终于通过简单地创建一个dontAllowTimeElapse最初设置为 false 的变量来解决这个问题。当用户停止动画并重新启动它时,dontAllowTimeElapse设置为 true:

         if (animated) {
            animated = false;
          } else {
            animated = true;

            dontAllowTimeElapse = true;
            performAnimation()
          }

在动画代码中,如果dontAllowTimeElapse为 true,则经过的时间重置为 0,这意味着动画从停止的地方重新开始。设置新中心后,再次允许时间流逝:

         if (dontAllowTimeElapse) {
            elapsed = 0;
          }
          before = now;
          earth.setCenter([c[0], c[1] + 0.1*(elapsed/30)]);
          dontAllowTimeElapse = false;
          requestAnimationFrame(animate);
于 2017-06-04T03:03:30.823 回答