【问题标题】:Play a Lottie / Bodymovin animation on scroll on an HTML web page在 HTML 网页上滚动播放 Lottie / Bodymovin 动画
【发布时间】:2019-03-12 22:34:06
【问题描述】:

我一直在搜索多个论坛以寻找解决此问题的方法 - 我正在尝试编写多个乐天动画以在每个动画进入 HTML 网页上的浏览器窗口时播放。有人有可行的解决方案吗?

我已经尝试了使用 Waypoint.js 的解决方案,但不幸的是,我无法使用该方法播放多个动画。如果有人知道如何让 Lottie 和 Waypoint 一起玩得很好,我将不胜感激。

我对任何脚本建议持开放态度,即使它们要求我加载依赖项以使其工作。任何帮助将不胜感激。另外,我应该注意,我是 Lottie 的新手,我是一名动画师,所以请留下详细的解释,因为我是 javascript 的初学者。

【问题讨论】:

    标签: javascript jquery-waypoints lottie bodymovin


    【解决方案1】:

    创建动画后,使用anim.goToAndStop(0)暂停它:

    const animData = ... // Let's pretend that you loaded this from a .json file
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.className = 'myAnimation';
    
    // Create the animation
    const anim = lottie.loadAnimation({
      renderer: 'canvas',
      loop: true,
      autoplay: false,
      rendererSettings: {
        context: ctx,
        scaleMode: 'noScale',
        clearCanvas: true,
      },
      animationData: animData,
    });
    
    // Go to the first frame and pause
    anim.goToAndStop(0);
    

    然后,您可以使用 OnScreen (https://github.com/silvestreh/onScreen) 之类的东西来检测动画何时可见:

    import OnScreen from 'onscreen';
    const os = new OnScreen();
    
    os.on('enter', '.myAnimation', (element, event) => {
        anim.play(); // If animation becomes visible, play it
    });
    
    os.on('leave', '.myAnimation', (element, event) => {
        anim.goToAndStop(0); // If animation goes off screen, reset it
    });
    
    

    以上适用于单个动画,但稍作调整后,可以扩展到多个动画。

    【讨论】:

      【解决方案2】:

      这里有一个简单的解决方案:

      var container = document.getElementById('graph_ani'); animData = bodymovin.loadAnimation({ container: container, renderer: 'svg', autoplay: false, loop: false, path : 'graph.json' });

      var animationStart = 0;
      $(window).scroll(function(){
          animData.playSegments([animationStart,animationStart+1], true);
          animationStart++;
      }
      

      可以使用一些工作仅在可见时播放并在向下滚动时播放并在向上滚动时反向播放,但对于快速 sn-p 效果很好。

      【讨论】:

        猜你喜欢
        • 2020-10-24
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2020-02-08
        • 1970-01-01
        • 1970-01-01
        • 2018-03-18
        • 2022-10-02
        相关资源
        最近更新 更多