How to add animated svg via javascript?

<svg width="5cm" height="3cm" viewBox="0 0 500 300"> <path id="path1" d="M100,250 C 100,50 400,50 400,250" fill="none" stroke="blue" stroke-width="7.06" /> <circle r="17.64" fill="red"> <animateMotion dur="6s" repeatCount="1" rotate="auto" > <mpath xlink:href="#path1"/> </animateMotion> </circle> </svg> 

If I write svg in the plain html / svg file, it works fine, circles are expecting correctly. But if I add a circle element dynamically through javascript, a circle is added, but it has not come to life. What's wrong? js code:

  var svg = $("svg"); //use jquery var circle = document.createElementNS("http://www.w3.org/2000/svg","circle"); circle.setAttribute("r", "5"); circle.setAttribute("fill", "red"); var ani = document.createElementNS("http://www.w3.org/2000/svg","animateMotion"); ani.setAttribute("dur", "26s"); ani.setAttribute("repeatCount", "indefinite"); ani.setAttribute("rotate", "auto"); var mpath = document.createElementNS("http://www.w3.org/2000/svg","mpath"); mpath.setAttribute("xlink:href", "#path1"); ani.appendChild(mpath); circle.appendChild(ani); svg.append(circle); 
+4
source share
2 answers

Use setAttributeNS in "mpath" instead of setAttribute .

 mpath.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#path1"); 

Here is a demo: http://jsfiddle.net/zh553/

+6
source

Accept using setAttributeNS in "mpath" instead of setAttribute .

However, at least for Chrome (and other WebKit-based browsers?), You need to pay attention to http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS where the second parameter says is the qualified name, the qualified attribute name to create or modify.

 mpath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#path1"); 

Or, if necessary, more general:

 mpath.setAttributeNS("http://www.w3.org/1999/xlink", mpath.lookupPrefix("http://www.w3.org/1999/xlink") + ":href", "#path1"); 

Also discussed at https://bugs.webkit.org/show_bug.cgi?id=22958

0
source

Source: https://habr.com/ru/post/1400917/


All Articles