Adding Lottie Animations to Svelte Application
Ever animated something cool in Figma or Adobe After Effects? It's possible to implement those animations in a friendly web format with Lottie.
Creating Animations
Installing Lottie
npm install lottie-webAdding Lottie
An example of a lottie animation that'll play when clicked (hamburger menu animation) and reverse, when clicked again
<script>
import lottie from 'lottie-web';
import { onMount } from 'svelte';
export let path;
export let loop = false;
export let autoplay = false;
export let speed = 1;
let animationContainer;
let animation;
let isForward = true;
onMount(() => {
animation = lottie.loadAnimation({
container: animationContainer,
renderer: 'svg',
loop: loop,
autoplay: autoplay,
path: path
});
animation.setSpeed(speed); // Set the initial speed
});
function toggleAnimation() {
if (isForward) {
animation.setDirection(1); // Play forward
} else {
animation.setDirection(-1); // Play in reverse
}
animation.play();
isForward = !isForward; // Toggle the direction
}
</script>
<button bind:this={animationContainer} class="lottie-container" on:click={toggleAnimation}></button>Last updated