I want to , for a specific event, such as onclick, as a specific SVG element, change that SVG's animateMotion
element and play that animation again. My current code does replay the animation correctly, but does not change the path attribute
<!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>
Clicking multiple times plays the animation multiple times, yet path
does not change. The specific goal of this is to create an animation where the animation moves to where the mouse was clicked.
CodePudding user response:
The DOM class of <animateMotion
is SVGAnimateMotionElement
. That class has no path
property (see docs). So dot.path = "..."
is doing nothing.
Use dot.setAttribute("path", "...")
instead.
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>