Как добавить анимированный SVG через JavaScript? - PullRequest
5 голосов
/ 12 марта 2012
<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>

Если я напишу svg в виде обычного html / svg файла, он будет работать нормально, кружок анимируется правильно. Но если я добавлю элемент круга динамически с помощью javascript, круг будет добавлен, но он не анимирован. В чем дело? JS код:

    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);

Ответы [ 2 ]

6 голосов
/ 12 марта 2012

Используйте setAttributeNS в "mpath" вместо setAttribute.

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

Вот демоверсия: http://jsfiddle.net/zh553/

0 голосов
/ 04 апреля 2013

Согласитесь с использованием setAttributeNS в "mpath" вместо setAttribute.

Однако, по крайней мере, для Chrome (и других браузеров на основе WebKit?), Кажется, необходимо обратить внимание на http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS, где говорится, что вторым параметром является qualName, полное имя атрибута для создания или изменить.

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

Или, если необходимо, более обобщенно:

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

Также обсуждается на https://bugs.webkit.org/show_bug.cgi?id=22958

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...