How to Create Tweens in Svelte
If you want to animate the properties of an element over a fixed period of time in Svelte, you can use a tweened store:
Copied to clipboard!
<script>
import { tweened } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
const tweenConfig = {
duration: 1000,
easing: cubicOut
};
const rotate = tweened(0, tweenConfig);
const radius = tweened(0, tweenConfig);
const transform = () => {
$rotate = 720;
$radius = 100;
};
</script>
<div on:click={transform}
style="transform: rotate({$rotate}deg); border-radius: {$radius}%">
</div>
You can use the following options in a tweened
store:
delay
: The amount of time to delay the tween. It defaults to 0.duration
: The duration of the tween. By default, it is set to 400 milliseconds.easing
: An easing function. You can import predefined easing functions fromsvelte/easing
.interpolate
: An interpolate function, which allows you to tween between any value. For example, you can use D3.js interpolate package to tween between colors.
For the full list of available easing functions, you can refer to the official svelte docs. Svelte also provides an ease visualizer where you can play with different easings.
Resources:
π More Webtips
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: