JS:如何将链式动画保存为变量以播放、暂停等

JS: How to save chained animations as a variable to play, pause, etc

如果我想控制一个简单的动画,我可以将它设置为 header 变量,然后 header.play() 像这样:

  let header= element.animate({
      transform: ['scale(1)', 'scale(1.5)']
    }, {
      duration: 1000,
      fill: 'both'
    });
  
  header.play();

但是当我链接它以便使用 composite 将不同的动画一起发生时,这将不起作用,因为它是多个定义:

element.animate({
  transform: ['scale(1)', 'scale(1.5)']
}, {
  duration: 1000,
  fill: 'both'
});

element.animate({
  transform: ['rotate(0deg)', 'rotate(180deg)']
}, {
  duration: 1500,
  fill: 'both',
  composite: 'add'
});

我如何控制它们一起使用 play()pause()

您可以使用 DOM 事件(甚至承诺)链接两个单独的动画:

const firstPart = element.animate({
  transform: ['scale(1)', 'scale(1.5)']
}, {
  duration: 1000,
  fill: 'both'
});

firstPart.finished.then(() => {
  const secondPart = element.animate({
    transform: ['rotate(0deg)', 'rotate(180deg)']
  }, {
    duration: 1500,
    fill: 'both'
  });
  return secondPart.finished;
});

或者您可以创建具有多个关键帧的单个动画:

element.animate([
  { offset: 0, transform: 'scale(1)' },
  { offset: .6, transform: 'scale(1.5) rotate(0deg)' }
  { offset: 1, transform: 'scale(1.5) rotate(180deg)' }
], {
  duration: 2500,
  fill: 'both',
  composite: 'add'
});

如果需要,关键帧解决方案还允许同时为两个属性设置动画。然而,animating two transforms indepdently is a bit complicated.