有没有简单的方法使用Javascript将JSON数据分配给svg元素?

时间:2015-04-29 07:19:15

标签: javascript json svg

我是SVG的新手,并尝试使用它创建一个简单的图形。 但我不知道如何使用'for loop'动态分配JSON数据在SVG中绘制一个矩形。帮我获取1个循环并指定每个值来绘制我想要附加到SVG元素的矩形。

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
window.onload = function(){
var data = [  
{   
    "srno" : 1 ,
    "status" : "production" , 
    "duration" : 30,
    "color" : "#00ff00",
},
{
    "srno" : 2 ,
    "status" : "idle" , 
    "duration" : 5 ,
    "color" : "#ff0000"}];
  //Make an SVG Container
var svgContainer = d3.select("body").append("svg")
.attr("width", 720)
.attr("height", 50);
 //Draw the Rectangle
 var rectangle = svgContainer.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", machines [1].duration)
.attr("height", 50)
.attr("fill","green");//Here I want the color from JSON object
//And I want duration to be the width property, 
//Status be the tooltip , which is not working 
</script>   

1 个答案:

答案 0 :(得分:0)

这是工作结果..

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
window.onload = function(){
var data = [  
{   
"srno" : 1 ,
"status" : "production" , 
"duration" : 30,
"color" : "#00ff00",
},
{
"srno" : 2 ,
"status" : "idle" , 
"duration" : 5 ,
"color" : "#ff0000"}
];
for ( var i = 0 ; i < data.length ; i++){
var rect = document.createElementNS(svgNS,'rect');
var width = data [i].duration ;
rect.setAttribute('x',20);
rect.setAttribute('y',10);
rect.setAttribute('width',data[i].duration);
rect.setAttribute('height',50);
rect.setAttribute('fill',data[i].color);
}};
</script>