在HTML网页上的滚动上播放Lottie / Bodymovin动画



我一直在搜索多个论坛,以寻找解决此问题的解决方案 - 当每个动画都进入HTML网页上的浏览器窗口时,我正在尝试编码多个Lottie动画。有人有工作解决方案吗?

我尝试了使用waypoint.js的解决方案,但不幸的是,我无法获得一个动画来使用该方法。如果有人知道一种让Lottie和Waypoint效果很好的方法,我将感谢任何建议。

我对任何脚本建议都开放,即使他们要求我加载依赖性以使其正常工作。任何帮助将不胜感激。另外,我应该指出,我对洛蒂(Lottie)来说是新手,我是动画师,所以请留下详细的解释,因为我是JavaScript的初学者。

创建动画后,使用 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
});

上面的动画适用于单个动画,但是经过一些小调整,它可以扩展到多个动画。

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

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++;
}

可以使用一些工作只能在可见时播放,并在scrolldown上播放并在滚动时倒转,但可以很好地进行快速片段。

最新更新