拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 SVG:有没有办法让沿路径的线的起点设定影片,同时让终点保持静止?

SVG:有没有办法让沿路径的线的起点设定影片,同时让终点保持静止?

白鹭 - 2022-03-14 2105 0 0

我正在尝试为沿路径的 svg 线的起点设定影片,同时将线的终点保持在静态点。

我认为说明我的问题的最好方法是使用下面的 gif。左边是我到目前为止所做的作业。每个弧都是一个 svg 路径,使用简单的 css 进行影片处理rotate()(有关详细信息,请参见下面的代码)。

右边是我想要实作的 - 一条x1 and y1与旋转弧一起移动的线,同时将其保持x2 and y2在弧下方的静态点。

在 svg 方面我还不太熟练,所以如果我可以对标记进行任何改进以帮助实作我的目标,那对我来说很好。

const SingleMessage: React.FC<{ index: number, text: string[], fairy: fairyNames, lines: number, prevWidth: number }> = ({ prevWidth, index, text, lines, fairy }) => {
// Width of the message arc - base 11   14 for each line of text
const width = 11   14 * lines;
// Radius of the arc from 0,0 - offset by prevWidth
const radius = 205.5   prevWidth   width / 2;
// Calculate the d of the path according to the variables above
const arc = describeArc(0, 0, radius, 89, 180 - ((width) / 2) / radius / (Math.PI / 180));
// Start coordinates of the path (arc) that are used as coordinates for the circle at the start of the arc
const arcStart = arc.split(' ').slice(1, 3);
// Colors for each path
const fairyGradient = fairyColors.get(fairy)?.gradient;
// Ref to the whole svg group in order to animate it using rotate()
const messagesRef = useRef<SVGGElement>(null);

// Rotate the path to 0 on mount (starts at -100deg)
useEffect(() => {
    if (messagesRef.current)
        messagesRef.current.style.transform = "rotate(0)";
}, [messagesRef.current])

return (
    // Rotate the whole group by 100deg in order to initially hide it
    <g className="-rotate-[100deg] transition-transform duration-500" ref={messagesRef}>
        {/* Gradient along the path */}
        <defs>
            <linearGradient id={`gradient${index}`}>
                <stop offset="0%" stopColor={fairyGradient?.[0]} />
                <stop offset="100%" stopColor={fairyGradient?.[1]} />
            </linearGradient>
        </defs>
        {/* Arc container of the message */}
        <path id={`msg${index}`} d={arc} fill="none" stroke="#fff" strokeWidth={width} strokeLinecap="round" className="drop-shadow-[4px_4px_0_rgba(0,0,0,0.25)]" />
        {/* Border around the arc */}
        <path d={arc} stroke={`url(#gradient${index})`} strokeWidth={width - 4} strokeLinecap="round" fill='none' />
        {/* Circle at the sart of the message */}
        <circle cx={arcStart[0]} cy={arcStart[1]} r={width / 2 - 1} fill={`url(#gradient${index})`} stroke="#fff" strokeWidth="2" />
        {/* Text inside the message */}
        <text color="#446688" fontSize="12px" fontFamily="'Kiwi Maru'" className="text-outline-light">
            <textPath startOffset={width / 2 - 1   5} href={`#msg${index}`}>
                <tspan x="0" alignmentBaseline={lines > 1 ? "before-edge" : "central"} dy={lines > 1 ? -(width / 2)   4 : -1} >{text[0]}</tspan>
                {text.length > 1 && text.slice(1).map((v, i) => <tspan key={index.toString()   i} x="0" alignmentBaseline="before-edge" dy="1em">{v}</tspan>)}
            </textPath>
        </text>
    </g>
);

uj5u.com热心网友回复:

按照 Paul 的建议,我继续阅读requestAnimationFrame()并创建了一个钩子来执行影片而不是使用 css 转换。

我从CSS TricksMDN获得了我需要的信息

这是任何有兴趣的人的代码:

export const useAnimationFrame = (duration: number, delay: number, callback: (deltaTime: number) => void) => {
    // Request ID from requestAnimationFrame()
    const requestRef = useRef<number>();
    // Start Time of the animation
    const startTimeRef = useRef<number>();
    // Time of the previous animationframe
    const previousTimeRef = useRef<number>(0);

    // animate() is called recursivly until the duration is over
    const animate = (time: number) => {
        // Set the start time...
        if (startTimeRef.current === undefined) {
            startTimeRef.current = time;
        }

        // ...to calculate the elapsed time
        const elapsed = time - startTimeRef.current;

        // Do the animation if we have a new frame
        if (previousTimeRef.current !== time) {
            callback(elapsed);
        }

        // Only recurse if we still haven't reached the duration of the animation
        if (elapsed < duration) {
            previousTimeRef.current = time;
            requestRef.current = requestAnimationFrame(animate);
        }
    }

    // Start the animation
    useEffect(() => {
        // Add a delay if necessary
        const timeout = setTimeout(() => requestRef.current = requestAnimationFrame(animate), delay);
        // Cleanup
        return () => {
            clearTimeout(timeout);
            requestRef.current && cancelAnimationFrame(requestRef.current)
        };
    }, []);
}
...
    // End coordinates of the line connecting the start of the arc with the fairy icon
    const [[x, y], setXY] = useState([radius.toString(), "0"]);
    // Current rotation of the arc
    const [rotation, setRotation] = useState(-90);

    // Animation for the rotation of the arc
    useAnimationFrame(animationDuration, index < 5 ? index * 500 : 0, elapsed => {
        // Set the current rotation of the arc
        const currRotation = Math.min(0, elapsed * 90 / animationDuration - 90);
        setRotation(currRotation);

        // For all messages after the five predefined, animate the line together with the arc
        if (index >= 5) {
            const currEndAngle = Math.min(endAngle, elapsed * 90 / animationDuration   90);
            const circlePos = describeArc(0, 0, radius, 90, currEndAngle).split(' ');
            setXY([circlePos[1], circlePos[2]]);
        }
    })

    return (
        <g>
            {index >= 5 && <line stroke='#fff' strokeWidth="3" x1="200" y1="550" x2={x} y2={y} />}
            {/* Rotate the whole group by 90deg in order to initially hide it */}
            <g className="-rotate-90" style={{ transform: `rotate(${rotation}deg)` }}>
...
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *