【问题标题】:Dynamically change the path of an animateMotion SVG element on event在事件中动态更改 animateMotion SVG 元素的路径
【发布时间】:2022-01-12 04:03:31
【问题描述】:

我想,对于特定事件,例如 onclick,作为特定 SVG 元素,更改该 SVG 的 animateMotion 元素并再次播放该动画。我当前的代码确实正确地重放了动画,但没有改变路径属性

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>SVG Example</title>
    <style>
        * { padding: 0; margin: 0; }
    </style>
</head>
<body>


<script>
  window.addEventListener("click", function(e){
    var dot = document.getElementById("reddot");
     dot.path = 'M 0 0 H ' + (e.clientX) + ' V ' + (e.clientY);
     dot.beginElement();
  });
</script>
<svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">

  <circle cx="0" cy="0" r="2" fill="red">
    <animateMotion dur="5s" id="reddot" repeatCount="1" path="M 0 0 H 10 V 10" restart="always" />
  </circle>
</svg>

</body>
</html>

多次单击会多次播放动画,但path 不会改变。这样做的具体目标是创建一个动画,动画移动到鼠标点击的地方。

【问题讨论】:

    标签: javascript svg


    【解决方案1】:

    &lt;animateMotion 的 DOM 类是 SVGAnimateMotionElement。该类没有 path 属性 (see docs)。所以dot.path = "..." 什么都不做。

    请改用dot.setAttribute("path", "...")

    window.addEventListener("click", function(e){
        var dot = document.getElementById("reddot");
         dot.setAttribute("path", 'M 0 0 H ' + (e.clientX) + ' V ' + (e.clientY));
         dot.beginElement();
      });
    * { padding: 0; margin: 0; }
    <svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
      <circle cx="0" cy="0" r="2" fill="red">
        <animateMotion dur="5s" id="reddot" repeatCount="1" path="M 0 0 H 10 V 10" restart="always" />
      </circle>
    </svg>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 2016-06-08
      • 2013-10-30
      • 2015-04-18
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多