JavaScript中的循环动画,使用GreenSock TweenLite。

4

我在canvas(HTML5)中画了一个点。然后我想让这个点在一个圆形路径上动画。

我看到了一个使用时间差来设置x和y变量的示例,与时间有关。使用的一些变量和公式相当模糊,我已经忘记了我的物理知识。但是我已经对圆周运动进行了相当多的研究,所以我可以理解其中的一些内容。这是我的 codepen,展示了如何实现它。

基本上,这是我迄今为止确定的部分:

this.orbit    = 100; // this is the radius of the circular orbit
this.radius   = 5;   // orbiting object's radius
this.velocity = 50;  // yeah velocity but without direction, should be speed (agree?)

var angle = 0; starting angle of the point in the orbit inside the canvas's quadrant,

xy坐标设置为相对于画布坐标的位置。 首先通过将宽度和高度除以2来获取画布中心点 然后加上轨道半径与xy相对于初始位置在轨道上的位置(angle)乘积, 由于Math三角函数使用弧度,因此我们应该将其乘以PI180的商。

this.x = _width  / 2 + this.orbit * Math.cos(angle * Math.PI / 180)
this.y = _height / 2 + this.orbit * Math.sin(angle * Math.PI / 180)

// by doing the above, we now get the initial position of x and y in the orbit.

对我来说相当琐碎的是下面这些变量:_dx_dy,还有_magnitude

以下是点的动画方式:

Point.prototype.update = function(dt) {
     var dps   = this.orbit * 2 * Math.PI / this.velocity;
     var angle = (360 / dps) * dt / 1000 * -1;

     this.vx = this.vx * Math.cos(angle * Math.PI / 180) - this.vy*Math.sin(angle * Math.PI / 180);
    this.vy = this.vx * Math.sin(angle * Math.PI / 180) + this.vy*Math.cos(angle * Math.PI / 180);

     var _magnitude = Math.sqrt( this.vx * this.vx + this.vy * this.vy);

     this.vx = this.vx / _magnitude * this.velocity;
     this.vy = this.vy / _magnitude * this.velocity;

     this.x += this.vx * dt / 1000;
     this.y += this.vy * dt / 1000;
}

以下是脚本的执行结果:

  function animate () {
      dt = new Date() - ldt;

      if (dt < 500) {
        // context.clearRect(0, 0, canvas.width, canvas.height);
        point.update(dt);
        point.draw(context);
      };

      ldt = new Date();
      setTimeout(function() {
          window.requestAnimationFrame(animate);
      }, 1000 / 30)
  }

  ldt = new Date();
  animate();

对于像_dx _dy _magnitude这样不清楚的变量,我无法理解它是如何工作和变量vx vy的计算方式,我假设它们分别是相对于x和y的速度。

我想使用GreenSock TweenLite进行动画处理,方法如下:

  Point.prototype.update = function(p){
       var _to = {
           x: , // change the value of x
           y: , // change the value of y
           ease: Cubic.easeInOut,
           onComplete: function () { this.update(p) }
        }

        TweenLite.to(point, 2, _to)
  }

正如您所看到的,第一个参数是当前对象(点),第二个参数是时间,我认为这是速度,第三个参数是对象属性x和y的变化。

问题

我创建了codepen,现在如何使用gsap tweenlite来像我所做的那样动画圆形,我想使用tweenlite会使它更简单一些。


你的问题是什么?你想了解这个脚本(codepen链接)是如何工作的以及绿袜动画的基础代码吗? - Dilip
1个回答

3
在您的情况下,您正在尝试使用TweenLite来按直线飞行动画处理点,并且在每个新位置的点上触发TweenLite.to() 功能。使用TweenLite.to()函数的这种方法没有意义和性能,因为点的两个位置之间的距离太短。因此,这种方法将仅减慢您的动画,因为您想要动画化的是新位置中的点,而不是只是绘制它。 在这种情况下,最好的解决方案是尝试使用TweenLite的方法来动画化整个圆。 请看这篇文章:在圆周上动画化 特别是这些例子: 1)http://codepen.io/GreenSock/pen/jCdbq(不是画布,但它展示了主要思路)
TweenMax.to("#logo", 4, {rotation:360, transformOrigin:"40px -100px", repeat:10, ease:Linear.easeNone});

2) and http://codepen.io/rhernando/pen/kjmDo


主要思想 - 你不需要为TweenLite计算新的点,让它自己完成,只需告诉它如何移动你的对象即可。 - Ihor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接