【问题标题】:Change SVG animation speed dynamically without position jumping动态改变 SVG 动画速度而不跳位
【发布时间】:2015-04-30 07:56:56
【问题描述】:

我有一个简单的 SVG,其中有一个元素围绕圆形路径旋转。当用户悬停时,通过更改 dur 属性可以加快旋转速度。问题是元素在发生时会跳转到不同的位置。怎么解决?

$('g').hover(
  function() {
    $(this).find('animateMotion').attr('dur', '3s');
  },
  function() {
    $(this).find('animateMotion').attr('dur', '7s');
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg width='500' height='500'>
  <g>
    <path id='circle' d='M 250, 250 m -200, 0 a 200,200 0 1,0  400,0 a 200,200 0 1,0 -400,0' fill='none' stroke='red' stroke-width='10' />
    <circle cx="50" cy="50" r="40" fill="red" transform='translate(-50, -50)'>
      <animateMotion dur="7s" repeatCount="indefinite">
        <mpath xlink:href="#circle" />
      </animateMotion>
    </circle>
  </g>
</svg>

【问题讨论】:

    标签: animation svg path


    【解决方案1】:

    调整动画时间轴,使动画在同一点。

    var firstTime = true;
    $('g').hover(
      function() {
        $(this).find('animateMotion').attr('dur', '3s');
        if (firstTime) {
          firstTime = false;
          return;
        }
        document.getElementById("root").setCurrentTime(
          document.getElementById("root").getCurrentTime() * 3 / 7);
      },
      function() {
        $(this).find('animateMotion').attr('dur', '7s');
        document.getElementById("root").setCurrentTime(
          document.getElementById("root").getCurrentTime() * 7 / 3);      }
    );
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <svg id="root" width='500' height='500'>
      <g>
        <path id='circle' d='M 250, 250 m -200, 0 a 200,200 0 1,0  400,0 a 200,200 0 1,0 -400,0' fill='none' stroke='red' stroke-width='10' />
        <circle cx="50" cy="50" r="40" fill="red" transform='translate(-50, -50)'>
          <animateMotion dur="3s" repeatCount="indefinite">
            <mpath xlink:href="#circle" />
          </animateMotion>
        </circle>
      </g>
    </svg>

    【讨论】:

    • 这效果要好得多,但我第一次悬停时仍然会跳跃。之后,它确实可以完美运行,但在此之前仍然存在跳跃。
    • 因为动画启动很快。在您悬停一次并停止悬停之前,它不会变慢。这对我来说似乎很奇怪,但我想这是你的功能。
    • 对不起,我在最初的帖子中犯了一个错误,动画确实应该开始缓慢。你知道如何让动画的初始值变慢吗?
    • 我知道,但你真的应该尝试自己弄清楚。这很明显。
    • 你说得对,也许我今天过得很慢,但我没有马上看到。
    猜你喜欢
    • 2021-10-03
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    相关资源
    最近更新 更多