简体   繁体   English

Javascript:在视口中启动 Lottie animation

[英]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.我有简单的 Javascript 代码,我正在尝试制作一个脚本,其中 Lottie animation 可以在视口中启动。

Now, this is not working.现在,这行不通。

Is there any solution to how I can start Lottie animation when is in the viewport?在视口中时如何启动 Lottie animation 有什么解决方案吗?

Lottie animation has id jancovic and when is this element in viewport Lottie animation may start. Lottie animation 的 ID为 jancovic ,该元素何时出现在视口中 Lottie animation 可能会启动。

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花了我 30 分钟以上
(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据我所知,它的“lottie.loadAnination”而不是bodymovin
i think that, that's the old way of writing it.我认为,这是写它的旧方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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