【问题标题】:ReactJS + SVG: Animate path "d" on click for FireFoxReactJS + SVG:点击 FireFox 的动画路径“d”
【发布时间】:2020-01-06 11:09:38
【问题描述】:

这里的代码笔:https://codepen.io/sadpandas/pen/xxbpKvz

const [currentScreen, setCurrentScreen] = React.useState(0);

return (
    <React.Fragment>
    <div>
       <svg
        className="theSvg"
        width="156" height="600" viewBox="0 0 156 600" xmlns="http://www.w3.org/2000/svg">
        <path
            d={pathArray[currentScreen].path}
            stroke={pathArray[currentScreen].strokeColor}
            fill="none"
        >
        </path>
    </svg>
    </div>
    <div>
        <div>
        <button onClick={()=> setCurrentScreen(0)}>0</button>
        <button onClick={()=> setCurrentScreen(1)}>1</button>
        <button onClick={()=> setCurrentScreen(2)}>2</button>
    </div>
    </div>
</React.Fragment>

我正在尝试在单击按钮时改变 SVG 路径。 这在 Chrome 中完美运行,但在 Firefox 中忽略了转换。

我目前的理解是 Firefox 还不支持这种动画。 我在这里有什么选择?我应该回退到使用标签吗?

我见过一些使用标签的例子,但它们都只是转换,不是在点击时触发的。我必须使用 ReactJs 来解决这个问题,所以 JQuery 也是不可行的。 如果可能的话,我也想避免使用包,因为这是我整个应用程序中唯一会使用 SVG 变形的地方。

任何提示将不胜感激。谢谢!

【问题讨论】:

  • 在 SMIL 中实现动画。

标签: javascript css reactjs svg onclick


【解决方案1】:

最终使用了动画标签。现在可以在 Firefox 和 Chrome 上正常运行。

对于同时学习 SVG 动画的任何人: 代码笔:https://codepen.io/sadpandas/pen/GRgyrOJ?editors=1010


const ButtonAndStrings = () => {
    const [currentScreen, setCurrentScreen] = React.useState(0);
    const [oldScreen, setOldScreen] = React.useState(0);


    const handleClick = (index, currentScreen) => {
        setOldScreen(currentScreen)
        setCurrentScreen(index);
    }

    return (
        <>
            <SVGPathAnimation
                path={pathArray[oldScreen]}
                newPath={pathArray[currentScreen]}
            />
            <button onClick={()=> handleClick(0, currentScreen)}>0</button>
            <button onClick={()=> handleClick(1, currentScreen)}>1</button>
            <button onClick={()=> handleClick(2, currentScreen)}>2</button>
        </>
    )
}

SVG 有一个叫做“动画时间线”的东西。为了发生新的动画,需要重置浏览器的时间。在 react 的情况下,向 SVG 添加 ref 可以解决问题。

参考:This medium article Jacob Fletcher。

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2016-01-06
    • 1970-01-01
    • 2017-03-22
    • 2015-09-21
    • 1970-01-01
    相关资源
    最近更新 更多