我正在尝试对 svg 路径进行动画处理,使其在单击时消失。动画有效,但在动画结束时留下了一个点。
这是我的代码
export default function App() {
const [showPassword, setShowPassword] = useState(false);
return (
<button type="button" onClick={() => setShowPassword((prev) => !prev)}>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="#000"
strokeWidth="1.5"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
<motion.path
initial={{ pathLength: 1, opacity: 1 }}
animate={{ pathLength: showPassword ? 0 : 1 }}
exit={{ pathLength: 1 }}
transition={{ duration: 0.2, ease: "easeInOut" }}
strokeLinecap="round"
strokeLinejoin="round"
d="M3 3L21 21"
/>
</svg>
</button>
);
}
我期待动画完全删除 svg 路径。
您面临的问题可能是由于 SVG 路径的动画方式造成的。当您对
pathLength
属性进行动画处理以使路径消失时,路径的可见性会降低为零,但它可能会在末尾留下一个小点,因为动画引擎可能无法完全删除路径。
为了确保路径完全消失而不留下点,您可以使用不同的方法。您可以为路径的
pathLength
和 stroke
属性设置动画,而不是为 opacity
设置动画。
代码的更新版本:
import { useState } from "react";
import { motion } from "framer-motion";
export default function App() {
const [showPassword, setShowPassword] = useState(false);
return (
<button type="button" onClick={() => setShowPassword((prev) => !prev)}>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="#000"
strokeWidth="1.5"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
<motion.path
initial={{ stroke: "#000", opacity: 1 }}
animate={{ stroke: showPassword ? "none" : "#000", opacity: showPassword ? 0 : 1 }}
exit={{ stroke: "#000", opacity: 1 }}
transition={{ duration: 0.2, ease: "easeInOut" }}
strokeLinecap="round"
strokeLinejoin="round"
d="M3 3L21 21"
/>
</svg>
</button>
);
}
在这段代码中,我使用描边属性来控制路径的颜色,当你想隐藏路径时将其设置为“none”,当你想显示路径时将其设置回“#000”。