【发布时间】:2021-06-17 23:28:00
【问题描述】:
我想使用 Framer Motion 在 React 中为 svg 文本的字母轮廓设置动画,使线条从某个点开始,然后在一段时间内逐渐完成。我有以下示例代码
import { useState, useRef, useEffect } from "react";
import { motion } from "framer-motion";
import "./styles.css";
export default function App() {
const [letterLength, setLetterLength] = useState(0);
const letterRef = useRef();
useEffect(() => {
setLetterLength(letterRef.current.getTotalLength());
}, []);
return (
<svg
id="logo"
width="998"
height="108"
viewBox="0 0 998 108"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<mask
id="path-1-outside-1"
maskUnits="userSpaceOnUse"
x="0.867188"
y="0.21875"
width="998"
height="108"
fill="black"
>
<rect fill="white" x="0.867188" y="0.21875" width="998" height="108" />
<path d="M15.3672 105H1.86719V2.625H15.3672V105Z" />
</mask>
<motion.path
initial={{
strokeDasharray: letterLength,
strokeDashoffset: letterLength
}}
animate={{
strokeDasharray: letterLength,
strokeDashoffset: 0
}}
transition={{ duration: 2 }}
d="M15.3672 105H1.86719V2.625H15.3672V105Z"
stroke="#EAE3DC"
strokeWidth="2"
mask="url(#path-1-outside-1)"
ref={letterRef}
/>
</svg>
);
}
然而,上面的代码表现得很奇怪。在我不想要的预期结果之前,这条线似乎被动画了多次。使用 vanilla JS 和 CSS 为字母设置动画时,我没有这个问题。我认为这个问题与状态变量有关,但我不确定它到底是什么。
这是codesandbox上的代码。
【问题讨论】:
标签: reactjs svg framer-motion