可动画化

高效地为目标属性创建动画,使其在值频繁变化的情况下(如光标事件或动画循环)成为替代 animate()utils.set() 的理想选择。

Animatable 是使用从主 'animejs' 模块导入的 createAnimatable() 方法创建的:

import { createAnimatable } from 'animejs';

const animatable = createAnimatable(targets, parameters);

或者作为独立模块从 'animejs/animatable' 子路径 导入:

import { createAnimatable } from 'animejs/animatable';

参数

名称 接受
targets Targets
parameters Object可动画设置

返回

可动画化

一个Animatable实例暴露了可动画属性函数以 获取设置 值。

animatable.propertyName(value, duration, ease); // Triggers an animation
animatable.propertyName(); // Returns the current value

出于性能原因,只有 NumberArray<Number> 可以传递给可动画属性函数。

可动画的代码示例

import { createAnimatable, utils } from 'animejs';

const $demos = document.querySelector('#docs-demos');
const $demo = document.querySelector('.docs-demo.is-active');

let bounds = $demo.getBoundingClientRect();
const refreshBounds = () => bounds = $demo.getBoundingClientRect();

const animatableSquare = createAnimatable('.square', {
  x: 500, // Define the x duration to be 500ms
  y: 500, // Define the y duration to be 500ms
  ease: 'out(3)',
});

const onMouseMove = e => {
  const { width, height, left, top } = bounds;
  const hw = width / 2;
  const hh = height / 2;
  const x = utils.clamp(e.clientX - left - hw, -hw, hw);
  const y = utils.clamp(e.clientY - top - hh, -hh, hh);
  animatableSquare.x(x); // Animate the x value in 500ms
  animatableSquare.y(y); // Animate the y value in 500ms
}

window.addEventListener('mousemove', onMouseMove);
$demos.addEventListener('scroll', refreshBounds);
<div class="large centered row">
  <div class="col">
    <div class="square"></div>
  </div>
</div>
<div class="small centered row">
  <span class="label">Move cursor around</span>
</div>