javascript - 如何将 svg 动画重置为初始状态?

标签 javascript html svg svg-animate

我有一个类似这样的 SVG 动画:

function startAnimation() {
  document.querySelector('#anim-width').beginElement();
}
<svg width="100" viewBox="0 0 100 100">
  <rect id="box" x="10" y="10" fill="red" width="10" height="10">
    <animate
      id="anim-width"
      attributeName="width"
      from="10"
      to="80"
      dur="1s"
      fill="freeze"
      begin="click"
    />
    
    <animate
      attributeName="height"
      from="10"
      to="80"
      begin="anim-width.end + 0s"
      dur="1s"
      fill="freeze"
    />
  </rect>
</svg>

<br/>

<button onclick="startAnimation()">Start</button>

我要实现的是红框从10乘10开始,当点击按钮时,宽度从10扩大到80,然后宽度动画完成后高度扩大到80。

第一次播放时效果很好,但是再次单击按钮时高度从 80 而不是 10 开始,如何将所有内容重置为初始状态并重新播放整个动画?

我尝试在 startAnimation() 函数中添加 document.querySelector('#box').setAttribute('height', '10'); 但它没有' 似乎有效。

最佳答案

我正在添加一个元素 <set>在 rect 内,我在函数内启动 set 元素 function startAnimation()

<set>元素是设置属性值(在本例中为高度)的一种方式,就像持续时间为 0 的动画。

function startAnimation() {
  document.querySelector("#set").beginElement();
  document.querySelector("#anim-width").beginElement();
}
<svg width="100" viewBox="0 0 100 100">
  <rect id="box" x="10" y="10" fill="red" width="10" height="10">
    <animate id="anim-width" attributeName="width" from="10" to="80" dur="1s" fill="freeze" begin="click" />

    <animate id="anim-height" attributeName="height" from="10" to="80" begin="anim-width.end + 0s" dur="1s" fill="freeze" />

    <set id="set" attributeName="height" to="10"></set>
  </rect>
</svg>

<br />

<button onclick="startAnimation()">Start</button>

关于javascript - 如何将 svg 动画重置为初始状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68067502/

相关文章:

html - 链接的可点击区域

javascript - 数据中具有相同值的 d3 scale 的错误使用?

javascript - 用一个正则表达式解析复杂的字符串

javascript - 如何使信息框从悬停链接的右侧滑出?

javascript - 入门 - Controller 不是函数未定义

javascript - 提交按钮操作取决于字段是否与另一个表单匹配

javascript - 如何使用 Raphael JS 在悬停时将路径 curl 成螺旋形

xml - 在 cocos2d-x 中使用 xml

javascript - 根据属性值对对象进行排序

javascript - 如何确定输入的模式是 `Int,VarChar,Date,Time...` 等