Svelte
useAni
A Svelte utility that creates a reactive store to track the state of an animation timeline.
This primitive subscribes to a timeline's state and exposes it as a readable Svelte store. It's ideal when animated values need to be used within your component's markup or other reactive computations.
Example
<script>
import { onMount } from 'svelte';
import { a } from "@freestylejs/ani-core";
import { useAni } from '@freestylejs/ani-svelte';
// 1. Define the animation structure and create a timeline.
const myTimeline = a.dynamicTimeline(
a.ani({ to: { count: 100 }, duration: 5, timing: a.timing.linear() })
);
// 2. Use the utility to get the readable store and controller.
const [value, controller] = useAni(myTimeline, { count: 0 });
// 3. Play the animation on component mount.
onMount(() => {
controller.play({ from: { count: 0 } });
})
</script>
<div>
<!-- 4. The animated value is read from the store via auto-subscription. -->
<h1>Counter: {Math.round($value.count)}</h1>
<button on:click={() => controller.play({ from: { count: 0 } })}>
Start
</button>
</div>Usage & Concepts
Overview
The useAni primitive acts as a bridge between the @freestylejs/ani-core engine and Svelte's reactivity model. It takes a timeline instance and an initialValue, returning a readable Svelte store that updates on every animation frame, along with the timeline's controller. You can auto-subscribe to the store's value using the $ prefix.
When to Use
- Do use
useAniwhen you need the animated values to be part of Svelte's reactive system. - Do use it for animations that affect text content, attributes, or props.
- Don't use
useAnifor high-frequency style updates on a single element. For that,useAniRefis a better choice.