【问题标题】:SVG animate starts without being startedSVG 动画在未启动的情况下启动
【发布时间】:2021-03-03 19:12:08
【问题描述】:

我有一个在没有启动变量的情况下启动的内部 a:

<rect height={5} width={5}>
    <animate 
        attributeName="height" 
        from={5} to={10} dur="2s" 
        begin={start ? "0s": "indefinite}/></rect>

组件位于 SVG 内部,该 SVG 会重新渲染以更改“start”变量以启动动画。但是,无论我何时选择重新渲染,动画都会立即开始。因此,如果我一渲染它所在的页面就按下它,它就会正常工作。但是,如果我在 2 秒后重新渲染组件,动画将跳转到结束值。如果我在渲染组件所在的页面后 1 秒开始动画,那么动画将从中间播放。怎么回事?!

谢谢

【问题讨论】:

  • 缺少 = 符号?如果没有,请提供minimal reproducible example,即我们可以自己运行的东西。
  • 页面上还有其他动画吗?如果是这样,动画时间轴可能已经运行,所以如果你说从 0 秒开始但时间轴已经在 2 秒,那么动画将从 2 秒开始。
  • 对于代码格式化:复制并粘贴格式化的代码,第一行不缩进。然后,按 Strg+K。
  • 感谢所有快速回复。 @RobertLongson 是的,页面上还有其他动画,但它们都以相同的“触发器”开始。找到了解决方案!

标签: javascript reactjs typescript svg svg-animate


【解决方案1】:

beginend 时间,如果使用时不参考其他时钟,请始终参考文档的开头。因此,您不应将值设置为0s,而应使用其他参考。我想到了几种可能性:

  1. 从点击或其他事件开始。 begin 值采用&lt;id of event target element&gt;.&lt;event name&gt; 的形式:

     <rect id="grafic" height={5} width={5}>
       <animate id="animation" attributeName="height"
                from={5} to={10} dur="2s" begin="grafic.click"/>
     </rect>
    
  2. 从其他代码开始。 begin 值保持在 indefinite

     <rect id="grafic" height={5} width={5}>
       <animate id="animation" attributeName="height"
                from={5} to={10} dur="2s" begin="indefinite"/>
     </rect>
    

    但动画是通过 API 调用启动的:

     document.getElementById('animation').beginElement();
    
  3. 为了更接近 React 的感觉,在设置属性的时候定义一个 wallckock 值为“right now”:

     const rightnow = () => new Date().toLocaleTimeString()
    
     <rect id="grafic" height={5} width={5}>
       <animate id="animation" attributeName="height"
                from={5} to={10} dur="2s"
                begin={start ? `wallclock(${rightnow()})` : "indefinite"/>
     </rect>
    

【讨论】:

  • 啊,这证实了我的怀疑。我试图弄清楚如何解决它。据我所知,MDN 没有给我很多关于这些细节的文档。
  • 如何在不使用事件侦听器和 beginElement() 的情况下在布尔值为真时触发“开始”?
  • 另外,beginElement() 将不起作用,因为 getElementById 的类型是 HTMLElement 而不是 SVGAnimateElement。
  • 时间格式的完整规范和文档是here。至于API,你测试了吗? &lt;animate&gt; 元素的document.getElementById()document.querySelector() 的返回值应始终属于SVGAnimateElement 类并实现SVGAnimationElement。同样,id.click 语法应该适用于每个引用的元素,无论它是否来自 SVG 命名空间的 HTML。
  • 我只知道 VSCode 给了我一个错误而不是用它编译,但我会开始一个新的查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2012-07-25
  • 2021-11-17
相关资源
最近更新 更多