Handling animations in Svelte is an intuitive and powerful process that offers multiple approaches to implement animation effects, thereby enhancing the interactive experience of user interfaces. These approaches include CSS animations, the transitions module, and the animations module.
1. CSS animations
Svelte enables developers to directly implement standard CSS animations and @keyframes rules within the <style> tag of components. This approach is simple and intuitive, leveraging native browser support for optimal performance.
Example code:
svelte<style> @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .spinner { animation: spin 1s linear infinite; } </style> <div class="spinner">Loading...</div>
2. Transitions
Svelte provides the transition module, offering multiple transition effects such as fade, slide, and fly. These effects can be directly applied to element entry and exit animations. To use them, add directives like transition:fade to the relevant elements.
Example code:
svelte<script> import { fade, slide } from 'svelte/transition'; let visible = true; </script> <button on:click={() => visible = !visible}>Toggle</button> {#if visible} <div transition:slide={{ duration: 300 }}> Slide Transition </div> {/if}
3. Animations
For more complex animation needs, Svelte offers the animation module. Like transition, you can leverage functions such as tweened and spring to create more nuanced and controllable animation effects.
Example code:
svelte<script> import { tweened } from 'svelte/motion'; import { cubicOut } from 'svelte/easing'; const number = tweened(0, { duration: 1000, easing: cubicOut }); </script> {#await number} <p>Loading...</p> {:then num} <p>{num.toFixed(2)}</p> {/await} <button on:click={() => number.set(Math.random() * 100)}>Animate</button>
Through these methods, Svelte simplifies and enhances the implementation of animations in web applications. Its animation handling supports rich visual effects while optimizing performance and the development experience.