Search code examples
sveltetween

How can svelte ease between two colors?


Does svelte have built-in support for tweening/easing between two colors, or should I write my own interpolation function for that?

I want a div to change background color, and I could supply the CSS color any way.


Solution

  • There is no built-in support for this, you have to add this yourself. The API docs however show you exactly this example as a custom tweener using d3-interpolate

    <script>
        import { interpolateLab } from 'd3-interpolate';
        import { tweened } from 'svelte/motion';
    
        const colors = [
            'rgb(255, 62, 0)',
            'rgb(64, 179, 255)',
            'rgb(103, 103, 120)'
        ];
    
        const color = tweened(colors[0], {
            duration: 800,
            interpolate: interpolateLab
        });
    </script>
    
    {#each colors as c}
        <button
            style="background-color: {c}; color: white; border: none;"
            on:click="{e => color.set(c)}"
        >{c}</button>
    {/each}
    
    <h1 style="color: {$color}">{$color}</h1>