javascripthtmlweb-animations

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


If i want to control a simple animation, I can set it to header variable and then do header.play() like this:

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

but when I chain it so that different animations happen together using composite, that won't work since it's multiple definitions:

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'
});

how would I control these together to make use of play(), pause() ?


Solution

  • You can either chain two separate animations using DOM events (or even promises):

    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;
    });
    

    Or you can create a single animation with multiple keyframes:

    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'
    });
    

    The keyframes solution also allows animating both properties at the same time if you want. However, animating two transforms indepdently is a bit complicated.