Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

start animation when lottie player element is visible on the screen #321

Open
Arunjenson-ss opened this issue Mar 13, 2024 · 1 comment
Open
Assignees
Labels
question Further information is requested

Comments

@Arunjenson-ss
Copy link

how to start the dot lottie animation when the lottie player is visible on the screen not when rendered on the screen

@afsalz afsalz self-assigned this Mar 18, 2024
@afsalz afsalz added the question Further information is requested label Mar 21, 2024
@afsalz
Copy link
Contributor

afsalz commented Mar 21, 2024

Hi @Arunjenson-ss,

If you're using the web component version of our player, you're in luck! This functionality is inherently supported. The player automatically begins playing the animation once it becomes visible on the screen. You can refer to the implementation here for more details: dotLottie Player Component - Visibility Feature.

If you are using the React player (@dotlottie/react-player), this feature isn't built-in as of now. However, you can achieve the desired behavior by utilizing the IntersectionObserver API.

import { DotLottiePlayer } from '@dotlottie/react-player';
import React, { useCallback, useEffect, useRef, useState } from 'react';

const Player = () => {
  const player = useRef(null);
  const [ready, setReady] = useState(false);

  const getObserver = useCallback(() => {
    return new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          player.current?.play();
        } else {
          player.current?.pause();
        }
      });
    });

  } , [player]);

  useEffect(() => {
    const observer = getObserver();
    if (player.current && ready) {
      observer.observe(player.current.container)
    }

    return () => {
      observer.disconnect();
    }
  }, [player, getObserver, ready]);

  return (
    <div>
      <DotLottiePlayer
        lottieRef={player} 
        autoplay={false} 
        onEvent={(event) => {
          if (event === 'ready') {
            setReady(true);
          }
        }}
        loop 
        src="https://lottie.host/lottie.json" />
    </div>
  );
};

export default Player;

Hope this helps you implement the visibility-based playback control in your project. Let us know if you have any more questions or need further assistance!

kenvlo pushed a commit to kenvlo/Lottie-Showcase that referenced this issue Jul 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants