弹簧

一个弹簧曲线生成器,返回一个缓动函数及其对应的持续时间,用于创建基于物理的动画。

spring() 方法可以直接传递给 ease 参数,用于 animate() 方法:

import { animate, spring } from 'animejs';

animate(target, { x: 100, ease: spring({ bounce: .5 }) });

动画的duration参数会被弹簧计算出的稳定持续时间覆盖。

感知参数

这些参数提供了对生成曲线更直观和可预测的控制,重点在于视觉 感觉 而非底层物理
。在使用感知参数时,物理值会使用 苹果的 SwiftUI 弹簧模型自动计算。

animate(target, { x: 100, ease: spring({ bounce: .5, duration: 350 }) });
名称 类型 信息
bounce Number 控制动画的“弹性”。范围:-11。默认值:0.5。从 01 的值会产生有弹性的曲线,低于 0 的值会产生过阻尼曲线。建议将 bounce 值保持在 -0.50.5 之间,否则超出此范围的值会产生非常极端的曲线,并且与 duration 参数的配合效果不佳。
duration Number 当动画在视觉上 感觉 完成时,感知的持续时间(毫秒)。范围:1010000。默认值:628

物理参数

对底层弹簧物理模型的直接控制。在需要对物理模拟进行更精确控制时使用这些。

animate(target, { x: 100, ease: spring({ stiffness: 95, damping: 13 }) });
名称 类型 信息
mass Number 连接到弹簧的对象质量。范围:110000。默认值:1。值越高,惯性越大,运动越慢、越沉重。
stiffness Number 弹簧刚度系数。范围:010000。默认值:100。较高的值会产生更紧的弹簧,使响应更快、更激烈。
damping Number 阻碍运动的阻尼系数。范围:010000。默认值:10。控制振荡衰减的速度。数值越高,反弹越小。
velocity Number 动画的初始速度。范围:-1000010000。默认值:0。正值会使动画在目标方向上有一个“运行加速”。

感知到的 onComplete 回调

这只适用于 JS 版本的animate()

动画的onComplete回调是相对于弹簧的稳定持续时间调用的,这会在动画感觉完成的时刻与实际回调调用之间产生视觉上的脱节。
为了解决这个问题,可以在弹簧参数对象上定义一个单独的onComplete回调,并将在弹簧感知的duration达到时调用。

animate(target, {
  x: 100,
  onCompete: () => console.log('called when the setting duration is reached'),
  ease: spring({ 
    bounce: .25,
    duration: 350,
    onCompete: () => console.log('called when the spring perceived duration is reached'),
  })
});
名称 类型 信息
onComplete Function 当弹簧达到其感知持续时间(而不是稳定持续时间)时触发回调。当动画对观众 看起来 完成时触发。

例子

名称 编辑器链接
默认弹簧 在编辑器打开
灵活的弹簧 在编辑器打开
弹跳的弹簧 在编辑器打开
强劲的弹簧 在编辑器打开

弹簧示例代码

import { animate, spring, utils } from 'animejs';

const [ $square1, $square2, $square3 ] = utils.$('.square');

utils.set('.square', { color: 'var(--hex-red-1)' })

animate($square1, {
  x: '17rem',
  rotate: 360,
  onComplete: () => utils.set($square1, { color: 'var(--hex-green-1)' }),
  ease: spring({
    bounce: .15,
    duration: 500,
    onComplete: () => utils.set($square1, { color: 'var(--hex-yellow-1)' }),
  })
});

animate($square2, {
  x: '17rem',
  rotate: 360,
  onComplete: () => utils.set($square2, { color: 'var(--hex-green-1)' }),
  ease: spring({
    bounce: .3,
    duration: 500,
    onComplete: () => utils.set($square2, { color: 'var(--hex-yellow-1)' }),
  })
});

animate($square3, {
  x: '17rem',
  rotate: 360,
  onComplete: () => utils.set($square3, { color: 'var(--hex-green-1)' }),
  ease: spring({
    stiffness: 90,
    damping: 14,
    onComplete: () => utils.set($square3, { color: 'var(--hex-yellow-1)' }),
  })
});
<div class="medium row">
  <div class="square"></div>
  <div class="padded label">{ bounce: .15, duration: 500 }</div>
</div>
<div class="medium row">
  <div class="square"></div>
  <div class="padded label">{ bounce: .3, duration: 500 }</div>
</div>
<div class="medium row">
  <div class="square"></div>
  <div class="padded label">{ stiffness: 90, damping: 14 }</div>
</div>