可动画

高效地对目标属性进行动画处理,使其成为 animate()utils.set() 的理想替代方案,适用于鼠标事件或动画循环等值频繁变化的场景。

Animatable 是通过从主 'animejs' 模块导入的 createAnimatable() 方法创建的

import { createAnimatable } from 'animejs';

const animatable = createAnimatable(targets, parameters);

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

import { createAnimatable } from 'animejs/animatable';

参数

名称 接受
targets 目标
参数 一个包含 Animatable 设置Object(对象)

返回

可动画

Animatable 实例通过暴露可动画属性函数来 获取设置 值。

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

出于性能考虑,只能将 Number(数字)或 Array<Number>(数字数组)传递给可动画属性函数。

Animatable 代码示例

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>