Search code examples
next.jsframer-motion

Using useTransform of framer-motion to clip-path


I tried to animate the clip-path using useTransform of framer-motion, but the value of useTransform it's like not compatible to style: clipPath

Here's my code:

Full Code

When animating the x and y of translate using useTransform it's okay, but in clip-path it's the value of useTransform is not compatible

Error


Solution

  • useTransform returns a motion value, which is why you are seeing [object Object] when putting them in the string template. Framer Motion has a solution to adding a motion value to string templates called useMotionTemplate. Here is how you would use it in your code:

    const clipPath1 = useTransform(scrollYProgress, [0, 1], [8, 0]);
    const clipPath2 = useTransform(scrollYProgress, [0, 1], [92, 100]);
    
    const clipPath = useMotionTemplate`polygon(${clipPath1}% 0px, ${clipPath2}% 0px, ${clipPath2}% 100%, ${clipPath1}% 100%)`;
    
    ...
    
    <motion.div
      style={{ clipPath }}
      ...
    >
      ...
    </motion.div>
    

    Here is a working example.