2014-03-02 44 views
0

我對頁面加載有要求我需要創建'圖像'屬性並將其附加到svg元素以啓動動畫。但是,我試圖創建圖像和關聯的animate元素並將其附加到svg元素。圖像正在顯示在頁面上,但它沒有變成動畫。如何動態創建svg元素併爲圖像添加動畫

任何人都可以在這方面提供幫助。

代碼添加在 http://jsbin.com/dofun/1/edit?html,js,output

由於 帕庫馬爾

+0

你可以發佈代碼,最好在jsfiddle或jsbin上。當我們沒有什麼可看的時候,很難提供幫助! – Ian

+0

ian,代碼添加在http://jsbin.com/dofun/1/edit?html,js,output – pavan

+0

你想把svg放在''標籤中,還是嵌入在html中?您的代碼使用'createElementNS'與svg命名空間結合使用,但使用標記。 appendChild不起作用,因爲沒有標識爲「svg_image」的元素。 –

回答

1

設置的持續時間的動畫是強制性的。如果你添加

animate.setAttribute('dur', '3s'); 

它爲我提供了正確的動畫,只要我添加一個svg元素和一個合適的id。

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>JS Bin</title> 
</head> 
<body> 
    <svg width="100%" height="100%" id="svg_image"/> 
</body> 
</html> 

body, html { 
    width : 100%; 
    height: 100%; 
} 

var img = document.createElementNS('http://www.w3.org/2000/svg','image'); 
    img.setAttributeNS(null,'height','536'); 
img.setAttributeNS(null,'width','536'); 
img.setAttributeNS('http://www.w3.org/1999/xlink','href','https://upload.wikimedia.org/wikipedia/commons/2/22/SVG_Simple_Logo.svg'); 
img.setAttributeNS(null,'x','10'); 
img.setAttributeNS(null,'y','10'); 
img.setAttributeNS(null, 'visibility', 'visible'); 
img.setAttributeNS(null,'id','image_test'); 


// animate object 

var animate = document.createElementNS('http://www.w3.org/2000/svg','animate'); 
animate.setAttributeNS(null,'attributeName','x'); 
animate.setAttributeNS(null,'from',500); 
animate.setAttributeNS(null,'to',0); 
animate.setAttribute('dur', '3s'); 
//append animate with image 
img.appendChild(animate); 

document.getElementById("svg_image").appendChild(img);