SVG元素在容器的左上角说

时间:2014-11-26 03:26:29

标签: javascript html css svg

SVG新手。我跟踪了一些SVG样本,我能够手动创建元素。现在我试图从Json文件创建SVG元素。元素在页面上创建,但它们不会显示在相应的坐标上。

下面的示例您将看到所有矩形处于相同位置,而它们应该分散在页面中。我真的不明白为什么不工作。

var svg = document.getElementById("mySVG"),
    xmlns = "http://www.w3.org/2000/svg";

 var c=[];
c.push(["valu1",13,240]);
c.push(["valu10",130,240]);
c.push(["valu2",120,250]);
c.push(["valu3",130,250]);
c.push(["valu4",140,54]);
c.push(["valu5",130,25]);

for(var i in c) {
   var myLoc = document.createElementNS(xmlns, "rect");
   var xPos =   c[i][1],
       yPos = c[i][2],
       id = c[i][0];

//to create a circle, for rectangle use rectangle
myLoc.setAttribute( "id", id);
myLoc.setAttribute( "cx", xPos);
myLoc.setAttribute( "cy",yPos);
myLoc.setAttribute( "height", 10);
myLoc.setAttribute( "width", 10);
myLoc.setAttribute( "stroke", "yellow");
svg.appendChild(myLoc);
}

以下是更新后的JSFIDDLE

2 个答案:

答案 0 :(得分:0)

SVG矩形使用xy而非cxcy

 var svg = document.getElementById("mySVG"),
    xmlns = "http://www.w3.org/2000/svg";

 var c=[];
c.push(["valu1",13,240]);
c.push(["valu10",130,240]);
c.push(["valu2",120,250]);
c.push(["valu3",130,250]);
c.push(["valu4",140,54]);
c.push(["valu5",130,25]);

for(var i in c) {
   var myLoc = document.createElementNS(xmlns, "rect");
   var xPos =   c[i][1],
       yPos = c[i][2],
       id = c[i][0];

//to create a circle, for rectangle use rectangle
myLoc.setAttribute( "id", id);
myLoc.setAttribute( "x", xPos);
myLoc.setAttribute( "y",yPos);
myLoc.setAttribute( "height", 10);
myLoc.setAttribute( "width", 10);
myLoc.setAttribute( "stroke", "yellow");
svg.appendChild(myLoc);
}

<强> DEMO

答案 1 :(得分:0)

试一试:JSFIDDLE

您的ID不是var而且还有一个问题rect XY不是cxcy

myLoc.setAttribute( "id", id);

创建动态ID

myLoc.setAttribute( "id", "id"+i);//here i is under loop