在事件上动态更改 animateMotion SVG 元素的路径

Dynamically change the path of an animateMotion SVG element on event

我想针对特定事件(例如 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不变。这样做的具体目标是创建一个动画,动画移动到鼠标点击的地方。

<animateMotion的DOMclass是SVGAnimateMotionElement。那class没有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>