如何在两种颜色之间轻松过渡?

问题描述 投票:0回答:2

svelte 是否内置支持两种颜色之间的补间/缓动,或者我应该为此编写自己的插值函数?

我想要一个 div 来更改背景颜色,并且我可以以任何方式提供 CSS 颜色。

svelte tween
2个回答
1
投票

没有对此的内置支持,您必须自己添加。然而,API 文档 准确地向您展示了这个示例,使用

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>

0
投票

基于这个示例我创建了以下自定义补间:

import { tweened } from "svelte/motion"

const tweenedHex = (hexadecimalString: string, duration = 500) => {
    const decimalToHex = (decimal: number) =>
        Math.round(decimal).toString(16).padStart(2, "0")

    const getColor = (hex: string, index: number) =>
        parseInt(hex.slice(index, index + 2), 16)

    const getRGBs = (hex: string) => [
        getColor(hex, 1),
        getColor(hex, 3),
        getColor(hex, 5),
    ]

    const scaledValue = (start: number, delta: number, t: number) =>
        start + delta * t

    function rgbInterpolate(fromColor: string, toColor: string) {
        const [fromRed, fromGreen, fromBlue] = getRGBs(fromColor)
        const [toRed, toGreen, toBlue] = getRGBs(toColor)
        const deltaRed = toRed - fromRed
        const deltaGreen = toGreen - fromGreen
        const deltaBlue = toBlue - fromBlue

        return (t: number) => {
            const red = scaledValue(fromRed, deltaRed, t)
            const green = scaledValue(fromGreen, deltaGreen, t)
            const blue = scaledValue(fromBlue, deltaBlue, t)
            return "#" + decimalToHex(red) + decimalToHex(green) + decimalToHex(blue)
        }
    }

    const color = tweened(hexadecimalString, {
        duration,
        interpolate: rgbInterpolate,
    })

    return color
}

export default tweenedHex

然后,我以与以下示例组件相同的方式使用此自定义补间:

<script lang="ts">
    import tweenedHex from "../store/tweenedHex"

    let color = "#ff0000"
    const tweenedColor = tweenedHex(color)

    $: tweenedColor.set(color)
</script>

<span>
    <input
        type="color"
        name="color-input"
        id="color-input"
        bind:value={color}
    />
    <span style:font-size="32px" style:color={$tweenedColor}>
        Tweened Color
    </span>
</span>

<span>color = {$tweenedColor}</span>

我对这个框架还很缺乏经验,但这样我就能够满足我的精简组件中与颜色过渡相关的所有需求。希望这有帮助!😄

© www.soinside.com 2019 - 2024. All rights reserved.