2012-03-12 97 views
4
<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代碼:如何通過javascript添加動畫SVG?

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

您可以發佈完整的HTML文件,而不是該段還討論?我不知道你用什麼JS框架來選擇SVG。如果您將SVG標記嵌入或嵌入嵌入標記,這將很高興。 – nak 2012-03-12 02:54:40

回答

6

上 「的mpath」 使用setAttributeNS而不是setAttribute

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

這裏有一個演示:http://jsfiddle.net/zh553/

+0

非常感謝,它的作品!正如你所說,我用「的setAttribute」的方法對錯誤「的mpath」 – dencey 2012-03-12 05:22:50

+0

@dencey沒有問題,這是一個有趣的問題:) – 2012-03-12 05:23:54

0

使用上 「的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