liushuangls / memo

用于记录
1 stars 0 forks source link

Web Animations API #53

Open liushuangls opened 6 years ago

liushuangls commented 6 years ago

polyfill

Element.animate():用于在元素上创建和播放动画的快捷方式。 它返回创建的Animation对象实例。

基本用法

首先创建一个对应于我们的CSS @keyframes块的关键帧对象

var aliceTumbling = [
  { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
  { color: '#431236', offset: 0.3},
  { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
];

与CSS不同,Web动画API不需要明确地告知每个键出现的动画的百分比。 它将根据您给出的按键数量自动将动画划分为相等的部分。

当我们想要明确地设置一个键与其他键的偏移量时,我们可以直接在对象中指定一个偏移量,并与逗号分隔。 在上面的例子中,为了确保的颜色变化为30%而不是50%,我们给它的偏移量为0.3。

我们还需要创建一个定时属性的对象 (AnimationEffectTimingProperties) 对应于动画中的值:

var aliceTiming = {
  duration: 3000, // 动画时间
  iterations: Infinity, // 无限循环
  easing: linear // 默认值为linear
}

使用:

document.getElementById("alice").animate(
  aliceTumbling,
  aliceTiming
)

可以单独传递毫秒:

document.getElementById("alice").animate(
  [
    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
    { color: '#431236', offset: 0.3},
    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
  ], 3000);

播放控制

const animate = document.getElementById("alice").animate(
  aliceTumbling,
  aliceTiming
)

animate.pause(); // 暂停
animate.play();  // 启动

除了暂停和播放,我们可以使用以下动画方法:

事件侦听器: