2014-04-22 61 views
1

我在HTML中创建一个SVG图案,用户将能够改变颜色和大小等,但它不工作。SVG HTML不绘制SVG图案

我得到一个关于body onload函数的错误。然后将SVG图追加到我拥有的svg占位符。

下面是脚本:

<script> 
    var SVG = document.getElementById("svgArea"); 
    document.content.appendChild(SVG); 

function drawCircle() 
{ 


    var svgLink = "http://www.w3.org/2000/svg"; 
      var Centre = document.createElementNS(svgLink,"circle"); 

      Centre.setAttributeNodeNS(null,"id","Centre"); 
    Centre.setAttributeNodeNS(null,"cx",230); 
      Centre.setAttributeNodeNS(null,"cy",0); 
      Centre.setAttributeNodeNS(null,"r",75); 
      Centre.setAttributeNodeNS(null,"fill","centreColour"); 



    document.getElementById("svgArea").appendChild(Centre); 


    var group = document.getElementById("svgArea"); 
    group.setAttribute("transform","translate(230,0)"); 

} 
</script> 

然后body标签,我有以下几点:

<body onload="drawCircle()"> 

而对于网页我有以下代码的内容:

<div class="content"> 
<!-- SVG DIAGRAM --> 

    <svg id="SVG" style="background:pink" viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="690" height"400"> 

    <g id="svgArea"> 
    </g> 
    </svg> 
</div> 

错误:

[Error] TypeError: 'undefined' is not an object (evaluating 'document.content.appendChild') 
global code (SVG.html, line 33) 

[Error] TypeMismatchError: DOM Exception 17: The type of an object was incompatible with the  expected type of the parameter associated to the object. 
drawCircle (SVG.html, line 57) 
onload (SVG.html, line 107) 

我在哪里做错了什么?

感谢

这并不工作:

//Drawing Petals 
    for (var i = 0; i < numberOfPetals; i++) 
    { 
     var svgLink = "http://www.w3.org/2000/svg"; 
     var flowerPettle = document.createElementNS(svgLink,"ellipse"); 


     flowerPettle.setAttributeNS(null,"id","flowerPettle"); 
     flowerPettle.setAttributeNS(null,"ry", 230); 
     flowerPettle.setAttributeNS(null,"rx",0) 
     flowerPettle.setAttributeNS(null,"fill",petalColour); 

     var rotate = "rotate(" + (i*(360/numberOfPetals)) + " " + 300 + "," + 30 + ")"; 

     flowerPettle.setAttribute("transform",rotate); 


     document.getElementById("FlowerArea").appendChild(flowerPettle); 

    } 
+0

你应该使用'setAttributeNS()''而不是setAttributeNodeNS()'。除此之外,你的代码看起来很好,假设'svgArea'是已经在你的标记中的元素的ID –

+0

啊谢谢仍然得到这个错误: TypeError:'undefined'不是一个对象(评估'document.content。 appendChild') global codeSVG.html:34 SVG.html:61 – 40764627182

+0

使用'document.content'你试图选择'content'类的div吗? –

回答

0

有几件事你的代码错误。一个是createAttributeNode()调用。另一个是document.content参考。另外还有一些像奇怪的颜色值“centreColour”。

我把一个工作小提琴放在一起。希望它能帮助你在代码中运行。

Demo here