创建动画后,使用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
});
以上适用于单个动画,但通过一些小的调整,它可以扩展到多个动画。