Quiero, para un evento específico, como hacer clic, como un elemento SVG específico, cambiar el elemento animateMotion de ese SVG y reproducir esa animación nuevamente. Mi código actual reproduce la animación correctamente, pero no cambia el atributo de ruta
<!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> Al hacer clic varias veces, se reproduce la animación varias veces, pero path no cambia. El objetivo específico de esto es crear una animación donde la animación se mueva hacia donde se hizo clic con el mouse.
La clase DOM de <animateMotion es SVGAnimateMotionElement . Esa clase no tiene propiedad de path ( ver docs ). Entonces dot.path = "..." no está haciendo nada.
Use dot.setAttribute("path", "...") en su lugar.
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>