Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create SVG animation tag using JavaScript

I have this SVG circle with an animation:

 <circle cx="30" cy="50" r="15" fill="blue" stroke="black" stroke-width="1">
  <animateMotion path="M 0 0 H 300 Z" dur="8s" repeatCount="indefinite" />
</circle>

It works fine. I want to make the exact same thing using JavaScript so if I click a button, it would create the same circle with the same animation.

Here is my try:

    var animateMotion = document.createElementNS("http://www.w3.org/2000/svg", "animateMotion");
    animateMotion.setAttribute("dur", "8s");
    animateMotion.setAttribute("d", "M 0 0 H 300 Z");
    animateMotion.setAttribute("repeatCount", "indefinite");
    // Assuming that I already created my circle
    myCircle.appendChild(animateMotion);
like image 878
Timmy Avatar asked Mar 06 '26 06:03

Timmy


2 Answers

Maybe this is your problem:

In XML:

<animateMotion path= ... />

In JS:

animateMotion.setAttribute("d", ... ); //Should this be "path"?

Hope it helps,
regards m93a.

like image 119
m93a Avatar answered Mar 07 '26 19:03

m93a


    var animateMotion = document.createElementNS('http://www.w3.org/2000/svg','animateMotion');
    animateMotion.setAttribute("dur","3s");
    animateMotion.setAttribute("repeatCount","1");
    var mpath = document.createElementNS('http://www.w3.org/2000/svg','mpath');
    mpath.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#YourPath");
    animateMotion.appendChild(mpath);
like image 25
Dex Avatar answered Mar 07 '26 21:03

Dex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!