Open Arunjenson-ss opened 6 months ago
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!
how to start the dot lottie animation when the lottie player is visible on the screen not when rendered on the screen