Framer X » Animation » Example animations » 22. Color: Interpolation

22. Color: Interpolation

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

Open Framer Motion version in CodeSandbox

Code Component

export function CC22ColorInterpolation() {
    const x = useMotionValue(0)
    const background = useTransform(x, [-100, 0, 100], ["#A0D", "#60F", "#0BF"])

    return (
        <Frame size="100%" background={background}>
            <Frame
                // Visual & layout
                size={150}
                radius={75}
                backgroundColor="#fff"
                center
                // Dragging
                drag="x"
                dragConstraints={{
                    right: 0,
                    left: 0,
                }}
                // Transformation
                x={x}
            />
        </Frame>
    )
}

Framer Motion

export function FM22ColorInterpolation() {
    const x = useMotionValue(0)
    const background = useTransform(x, [-100, 0, 100], ["#A0D", "#60F", "#0BF"])

    return (
        <motion.div
            style={{
                width: "100%",
                height: "100%",
                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>
    )
}

Overrides

const x = motionValue(0)

export function Background(): Override {
    const background = useTransform(x, [-100, 0, 100], ["#A0D", "#60F", "#0BF"])
    return {
        background: background,
    }
}

export function Color_Interpolation(): Override {
    return {
        // Dragging
        drag: "x",
        dragConstraints: {
            right: 0,
            left: 0,
        },
        // Transformation
        x: x,
    }
}

Leave a Reply