在 svg 路径更改后再次执行动画

Make animate execute again after svg path changes

我想为 svg 路径制作动画,这样动画只 运行 一次,但是如果 d 值发生变化,则动画应该再次 运行 一次。每次路径值更改时我都遇到动画 运行 的问题,如果我将 repeatCount 值设置为 1,则在 svg 值更改和 svg“重新渲染”后它不会再次 运行。我在下面包含了一些代码,这些代码复制了我正在尝试做的事情,我们将不胜感激。这是一个只有动画的代码演示,没有反应:https://codepen.io/shak8/pen/RwLLjNm

const SVGAnimate = () =>{
    const [width, setWidth] = useState(213)
    const [prevWidth, setPrevWidth] = useState(213)
    return (
      <div>
         <svg width="400" height="500">
           <path  style="stroke-width:3;stroke:rgb(0,0,0)"
            fill="black"
            d=`M 0 212 S 226 212, ${width} 20 V 212 H 0`>
    
              <animate 
                attributeName="d"
                dur="5s"
                from=`M 0 212 S 226 212,${prevWidth} 20 V 212 H 0`
                to=`M 0 212 S 226 212, ${width} 20 V 212 H 0`

                repeatCount="1"
                fill="black"
                />
            </path>
            <button onClick={() => {
                                      // These should trigger svg path to change, desired
                                      // effect is for path to change with animation.
                                      setPrevWidth(width == width)
                                      setWidth(width == 213 ? 320 : 213)
                                   }
            }> Change</button>
      </div>
    )
}

我也试过在路径上使用过渡,它在 chrome 上完美运行,但在 safari 上不起作用。

您可以使用onClick="animation.beginElement()"

观察:动画有一个 fill="black" 属性。我想你的意思是 fill="freeze"。这将冻结动画,类似于 animation-fill-mode: forwards.

<div>
         <svg width="400" height="200">
           <path  style="stroke-width:3;stroke:rgb(0,0,0)"
            fill="black"
            d="M 0 212 S 226 212, 100 20 V 212 H 0">
    
              <animate id="animation"
                attributeName="d"
                dur="5s"
                from="M 0 212 S 226 212,100 20 V 212 H 0"
                to="M 0 212 S 226 212, 300 20 V 212 H 0"

                repeatCount="1"
                fill="freeze"
                />
            </path>
   </svg>
            <button onClick="animation.beginElement()"> Change</button>
      </div>