【问题标题】:How to add an animated svg via javascript?如何通过javascript添加动画svg?
【发布时间】:2013-04-04 17:30:58
【问题描述】:
<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>

如果我在普通的 html/svg 文件中编写 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);

【问题讨论】:

  • 你能发布完整的 HTML 文件而不是那个 sn-p 吗?我不知道您使用什么 JS 框架来选择 SVG。很高兴知道您是将 SVG 标记内联还是使用 embed 标记嵌入它。

标签: javascript svg


【解决方案1】:

在“mpath”上使用setAttributeNS 而不是setAttribute

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

这是一个演示:http://jsfiddle.net/zh553/

【讨论】:

  • 非常感谢,它有效!正如你所说,我错误地使用了“setAttribute”方法来“mpath”
  • @dencey 没问题,这是一个有趣的问题 :)
【解决方案2】:

同意在“mpath”上使用setAttributeNS 而不是setAttribute

但是,至少对于 Chrome(和其他基于 WebKit 的浏览器?),似乎有必要注意 http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS,它说第二个参数是qualifiedName,即要创建或更改的属性的限定名称。

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讨论过

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-28
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2022-01-08
    • 2022-01-05
    • 2019-07-26
    相关资源
    最近更新 更多