如何使用Framer Motion实现SVG路径从起点到终点消失的动画
实现路径从起点消失的修改方案
你只需要额外引入pathOffset属性控制路径的绘制偏移就能实现需求。SVG路径的可见区域默认是「从路径起点开始,长度等于pathLength」,所以单独修改pathLength的时候,缩短路径就是从终点往起点收。而pathOffset可以把可见区域的起始点沿着路径方向偏移,我们把pathLength固定为1(始终显示完整长度的可见段),让pathOffset从0变到1,可见段就会沿着路径从起点往终点方向“滑出”,看起来就是从起点开始逐步消失了。
具体修改点
保留原有的transition配置不变,仅修改motion.path的initial和animate属性,新增pathOffset配置即可:
<motion.path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" initial={{ pathLength: 1, pathOffset: 1 }} animate={{ pathLength: 1, pathOffset: 0 }} transition={transition} />
修改后完整代码
export default function App() { const transition = { duration: 2, repeat: Infinity, repeatType: "reverse", ease: "easeInOut" }; return ( <svg height="256" width="256" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" > <motion.path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" initial={{ pathLength: 1, pathOffset: 1 }} animate={{ pathLength: 1, pathOffset: 0 }} transition={transition} /> </svg> ); }
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

