如何截断jquery动画的开头?

问题描述 投票:2回答:1

不要对我很难,这是我第一次发帖。

我目前正在研究命运之轮,它通过node.js和websockets与每个连接的设备同步。但是,当用户在轮子已经旋转的情况下加入时,我想截断动画的开始,因此它仅显示动画的最后几秒钟,而不会改变其缓动性。

jquery动画由一个简单的步进动画组成,该动画会旋转轮子。我已经尝试过更改步骤“ fx”对象的参数,例如fx.start或fx.pos。尽管fx.start只是动画开始的变量,例如180度,而fx.pos只是一种输出参数,可以将某些内容更改为动画中的给定时间,例如文本颜色或其他内容。但是,不能更改fx.pos值,也不能更改当前设置动画的位置。我创建了一个函数,使命运之轮旋转两次,然后以给定的角度停止。

[我也尝试更改缓动,所以它将是50%的线性,50%的摆动,但是这会使动画看起来很杂乱,因为起初它以恒定的速度旋转,但突然间旋转的速度比慢的要快。

function spinRoulette(deg, duration = 10000) {
  deg = Math.round(deg);
  $("img.roulette").animate(
      { now: '+='+(720+deg-getRotation()) }, {
      duration: duration,
      ...
      step: function(now, fx) {
        if(now >= 360)
          now -= 360;
        $(this).css("transform", "rotate("+now+"deg)");
      }
    });
}

如果持续时间少于10秒,动画的开始将被切断。因此,如果服务器在大约5秒钟前旋转了轮子,则应删除动画的前5秒钟。

javascript jquery animation jquery-animate
1个回答
0
投票

在任何时间点赶上轻松的动画旋转

  • 线性动画t0或从10.N1.0(如果玩家在10秒内第6秒加入,则为0.6)$({t: t}).animate({t: 1},
  • Ease!在任何给定的“现在”时间点,使用自定义缓动函数]将当前的0.0-1.0时间范围(t_now值)转换为相应的缓动e_now值。
  • 缓和e_now结果乘以所需的结束度数

而不是使用"swing" 使用"linear"让我们控制放松和时间安排自定义放松功能(您可以找到许多放松片段online)。假设我们喜欢easeInOutSine

const easeInOutSine = t => -(Math.cos(Math.PI * t) - 1) / 2;

示例

有4个人的示例,一个人旋转轮子,其他参加演出在2、4.5和8.7秒时之后初始旋转开始

const easeInOutSine = t => -(Math.cos(Math.PI * t) - 1) / 2;

function spinRoulette(sel, deg, duration = 10000) {
  const $el = $(sel);
  const maxDuration = 10000;
  const deg_end = 720 + Math.round(deg);  // 2 revolutions + server-generated degrees
  const time = maxDuration - duration;    // Start time in ms
  const t = time / maxDuration;           // Start time to 0.0-1.0 range 

  $({t: t}).animate({t: 1}, {             // Custom jQuery anim. from 0.N to 1.0
    duration: duration,
    easing: "linear",                     // We need a linear 0.0 to 1.0
    step: function(t_now) {
      const e_now = easeInOutSine(t_now); // Current easing
      const deg_now = e_now * deg_end;    // Current degrees
      $el.css({transform: `rotate(${ deg_now }deg)`});
    }
  });
}

// Person 1 spins!
spinRoulette("#r1", 45);
// Person 2 joins the room after 2s
setTimeout(() => spinRoulette('#r2', 45, 10000 - 2000), 2000);
// Person 3 joins the room after 4.5s
setTimeout(() => spinRoulette('#r3', 45, 10000 - 4500), 4500);
// Person 4 joins the room after 8.7s
setTimeout(() => spinRoulette('#r4', 45, 10000 - 8700), 8700);
img {height: 120px; display: inline-block;}
<img id="r1" src="https://i.stack.imgur.com/bScK3.png">
<img id="r2" src="https://i.stack.imgur.com/bScK3.png">
<img id="r3" src="https://i.stack.imgur.com/bScK3.png">
<img id="r4" src="https://i.stack.imgur.com/bScK3.png">

<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>

在上面的示例中,最后,您可以注意到(除了一些奇怪的错觉),车轮在任何时间点以正确的旋转状态velocity追赶,并且所有车轮都同时完成精确的预定义deg_end度下的相同缓动。

© www.soinside.com 2019 - 2024. All rights reserved.