简体   繁体   中英

Javascript: start Lottie animation when is in viewport

I have simple Javascript code where I'm trying to make a script where Lottie animation may start when is in the viewport.

Now, this is not working.

Is there any solution to how I can start Lottie animation when is in the viewport?

Lottie animation has id jancovic and when is this element in viewport Lottie animation may start.

Already all is in if a statement is not changeable can't be the change I need to change only if the statement probably.

 var jancovic = document.getElementById('jancovic'); var boundingJancovic = jancovic.getBoundingClientRect(); window.onscroll = function() { if (boundingJancovic.top >= 0 && boundingJancovic.left >= 0 && boundingJancovic.right <= window.innerWidth && boundingJancovic.bottom <= window.innerHeight) { var svgContainerJancovic = document.getElementById('jancovic'); var animItemJancovic = bodymovin.loadAnimation({ wrapper: svgContainerJancovic, animType: 'svg', loop: false, path: '/assets/anim/graphs/data.json' }); } }

I was just looking for the same thing. took me a good 30min plus
(and a coffee) to get this working, so i hope this helps anyone

<script>
// kickstat the animation - mine is a div with the id of "headerAnimation"
// which sits inside a div with an id of "header"
var headerAnimation = lottie.loadAnimation({
    container: document.getElementById("headerAnimation"), // the dom element that will contain the animation
    renderer: "svg",
    loop: false,
    autoplay: true,
    path: "SOME_PATH_TO_FILE" // the path to the animation json
});


// "listen" & check when header is out of viewport 
// (i set 50% = visible => threshold: 0.5 (to set))
const headerViewport = function() {
    let options = {
        root: null,
        rootMargin: '0px',
        threshold: 0.5
    }

    let observer = new IntersectionObserver(function(entries, observer) {
        entries[0].isIntersecting === true ? headerAnimation.play() : headerAnimation.goToAndStop(0, 0);
    }, options);

    observer.observe(document.querySelector('#header'));
}

// on window load
window.onload = function() {
    headerViewport();
}
</script>

btw
as far as i can see, its "lottie.loadAnination" and not bodymovin
i think that, that's the old way of writing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM