chenqingspring / react-lottie

Render After Effects animations on React based on lottie-web
MIT License
1.66k stars 363 forks source link

Support `goToAndStop`? #40

Open jessepinho opened 6 years ago

jessepinho commented 6 years ago

Hi there,

I'm interested in being able to set the exact frame of the animation, so that I can sync the animation as the user scrolls down the page.

For now, I've created a subclass of Lottie that takes a percentage parameter and then uses it to set the frame:

export default class LottieWithAnimationControl extends Lottie {
  static propTypes = {
    ...Lottie.propTypes,
    percentage: PropTypes.number,
  }

  anim: any
  props: Props

  componentDidUpdate(prevProps: Props, prevState: any, prevContext: any) {
    if (super.componentDidUpdate) {
      super.componentDidUpdate(prevProps, prevState, prevContext)
    }

    if (this.props.percentage !== prevProps.percentage && this.anim.totalFrames) {
      const frame = Math.round(this.anim.totalFrames * this.props.percentage)
      this.anim.goToAndStop(frame, true)
    }
  }
}

However, what do you think of supporting this natively in the component?

felippenardi commented 6 years ago

I'd love to see that. Thanks for sharing your workaround!

felippenardi commented 6 years ago

@chenqingspring Hi Chen! Are you still maintaining this repo? Would you like help? There is some great feature like this one being suggested.

gigamesh commented 6 years ago

@jessepinho Thanks for this! I've been looking for something like it for days. :)

Is there any chance you could walk through how it works? I'm pretty new to JS and React, so I'd really appreciate the lesson. I roughly understand the last section calculating which frame to be on using a percentage received from the parent component, but I'm pretty confused about everything before that (aside from propTypes). These lines are particularly mysterious to me:

  anim: any
  props: Props

prevState: any, prevContext: any

wahlforss commented 5 years ago

@jessepinho Would also love a quick walkthrough!

jsargeim commented 5 years ago

@felippenardi @chenqingspring Anyone still attending to this repo? I'd love to help.

peterloveland commented 4 years ago

@gigamesh @wahlforss I'm hacking something together needing this basic functionality, using the code from @jessepinho I got this to work using the following, I've simplified down the use case a bit but the following is the 'barebones': (Basically I just removed all the bits that were confusing you and that seemed to do the trick)

import React from 'react';
import Lottie from 'react-lottie';

export class LottieWithAnimationControl extends Lottie {
  componentDidUpdate() {
    const frame = Math.round(this.anim.totalFrames * this.props.percentage)    
    this.anim.goToAndStop(frame, true)
  }
}