Search code examples
web-componentlottielit-html

Lottie player do not update the underlying animation when src attribute is changed at run time?


I was using lottie player for animated sticker on my PWA app. Now at run time when I change the src attribute of lottie player, it do not reloads a new animation. <lottie-player src=${state.url} background="transparent" speed="1" style="width: 100%; height: 100%;" loop autoplay></lottie-player> is there a way to force this animation to reload by changing the attribute ?

I am using lit-html as my templating library and custom framework for creating web components.


Solution

  • The lottie web player requires a programmatic load method call to change the animation. Their api doesn't update the animation based on a runtime src property change.

    Lit-html and web components are not required to answer the question, but I can provide a code sample using lit to show a working example.

    Example changing animation of Lottie web player: https://lit.dev/playground/#gist=4569b4b023db7014d45112679059296b

    See below for a minimal answer.

    class ExampleChangingAnimation extends LitElement {
      /**
       * Get the rendered Lottie player element
       */
      get lottiePlayer() {
        return this.shadowRoot.querySelector('lottie-player');
      }
    
      /**
       * changeAnimation gets the new animation src string and loads
       * it onto the Lottie web player.
       */
      changeAnimation () {
        // Get new animation to load.
        const newAnimation = "...animation url...";
    
        // Load the new animation on the lottie player element.
        this.lottiePlayer.load(newAnimation)
      }
    
      render () {
        return html`
          <lottie-player></lottie-player>
          <button @click=${this.changeAnimation}>Change Animation</button>
        `;
      }
    }