How to Create Tweens in Svelte

How to Create Tweens in Svelte

Ferenc Almasi β€’ 2020 October 18 β€’ Read time 2 min read
  • twitter
  • facebook

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>
Tween.svelte

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 from svelte/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.

How to Create Tweens in Svelte
If you would like to see more Webtips, follow @flowforfrank

Looking into Svelte 3

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.