Animation » Example Animations » 24. Colors: Interpolation

24. Colors: Interpolation

Here the useMotionValue() and useTransform() hooks are used to interpolate between three colors. (In the override: motionValue().)

Code component

Note that the middle ‘color’ is actually fully transparent, black with 0% opacity: "rgba(0,0,0,0)".

export default function CC_24_Colors_Interpolation(props) {
    const x = useMotionValue(0)
    const background = useTransform(
        x,
        [-100, 0, 100],
        ["#a0d", "rgba(0,0,0,0)", "#0bf"]
    )

    return (
        <motion.div
            style={{
                width: 400,
                height: 400,
                ...props.style,
                backgroundColor: background,
                display: "flex",
                placeItems: "center",
                placeContent: "center",
            }}
        >
            <motion.div
                style={{
                    width: 150,
                    height: 150,
                    borderRadius: 75,
                    backgroundColor: "#fff",
                    x: x,
                    cursor: "grab",
                }}
                drag="x"
                dragConstraints={{ right: 0, left: 0 }}
                whileTap={{ cursor: "grabbing" }}
            />
        </motion.div>
    )
}

Code overrides

const x = motionValue(0)

export function Background(Component): ComponentType {
    return (props) => {
        const { style, ...rest } = props

        const background = useTransform(
            x,
            [-100, 0, 100],
            ["#a0d", "rgba(0,0,0,0)", "#0bf"]
        )

        return (
            <Component
                {...rest}
                style={{ ...style, backgroundColor: background }}
            />
        )
    }
}

export function Colors_Interpolation(Component): ComponentType {
    return (props) => {
        const { style, ...rest } = props

        return (
            <Component
                {...rest}
                drag="x"
                dragConstraints={{ right: 0, left: 0 }}
                style={{ ...style, x: x }}
            />
        )
    }
}

Leave a Reply