svg如何做到一组动画循环

如果只有一个动画的话 **repeatCount="indefinite" 就可以了

<svg>
    <rect x='20' y='20' width='250' height='250' fill='blue'>
        <animate attributeType="CSS" attributeName="width" from="250" to="0" dur="1s" repeatCount="indefinite" />
    </rect>
</svg>

如果2个以上动画的话,怎么让两个动画作为一组循环

<svg>
    <rect x='20' y='20' width='250' height='250' fill='blue'>
        <animate attributeType="CSS" attributeName="width" from="250" to="0" dur="1s" />
        <animate attributeType="CSS" attributeName="width" from="0" to="250" begin='1s' dur="1s"/>
    </rect>
</svg>
阅读 13.6k
3 个回答

如果只是单纯的改变宽度,少年可以这样实现

<svg>
    <rect x='20' y='20' width='250' height='250' fill='blue'>
        <animate animateType="css" attributeName="width" values="250;0;250" dur="3s" repeatCount="indefinite"/>
    </rect>
</svg>

给animate添加id后,使用begin来指定动画开始的时间为另一个的结束。

不清楚有没有更好的办法。

<svg>
    <rect x="20" y="20" width="241.667" height="250" fill="blue">
        <animate attributeType="CSS" attributeName="width" begin="0s; second.end" id="first" from="250" to="0" dur="1s"></animate>
        <animate attributeType="CSS" attributeName="width" begin="first.end" id="second" from="0" to="250" dur="1s"></animate>
    </rect>
</svg>
新手上路,请多包涵

如果单纯只是实现动画效果,可以不使用animate,转而使用js控制
具体实现思路是使用js中的setInterval函数,每次更新相应的值(如题即width),设置边界条件
如下是我实现一个圆球循环滚动的代码及效果:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    circle {
      stroke-width: 5;
      stroke: #f00;
      fill: #ff0;
    }
  </style>
</head>

<body>
  <svg width="400px" height="100px" viewBox="0 0 400 100" style="background-color: thistle;">
    <circle cx="50" cy="50" r="50" fill="blue" id="circle" />
  </svg>

</body>
<script>
  const circle = document.getElementById('circle');
  let x = 50
  let distance = 3
  setInterval(() => {
    if (x > 350 || x < 50) distance = -distance
    x += distance
    circle.setAttribute('cx', x)
  }, 20);
</script>

</html>

球体循环滚动动画

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题