2016-02-21 24 views
1

我想在它下面画一个矩形和水平线。由于没有任何东西正在绘制,我无法弄清楚为什么。如果可能,我想保留基本结构(用于矩形和线条绘制的单独函数),因为我绘制了多个不同大小/长度的矩形和线条。我是新来的d3.js(和一般的js),所以任何改进都是值得欢迎的。d3js绘制svg矩形和线条问题

文件so_rect.js:

function Rectangle(x, y, height, width) { 
    this.x_axis = x; 
    this.y_axis = y; 
    this.height = height; 
    this.width = width; 
} 

function Line(x, y, width) { 
    this.x_axis = x; 
    this.y_axis = y; 
    this.width = width; 
} 

function renderLine(){ 
    console.log('>>renderLine'); 
    var line = new Line ('10', '55', '200'); 
    var stringifiedLine = JSON.stringify(line); 
    var jsonLine = JSON.parse(stringifiedLine); 
    var g = d3.select("#svgContainer"); 
    var lines = g.selectAll("line") 
     .data(jsonLine) 
     .enter() 
     .append("line"); 
    var lengthLines = lines 
     .attr("x1", function(d) { return d.x_axis; }) 
     .attr("x2", function(d) { return d.x_axis+ d.width; }) 
     .attr("y1", function(d) { return d.y_axis; }) 
     .attr("y2", function(d) { return d.y_axis+ 20; }) 
     .style("stroke", "black") 
     .style("stroke_width", 2); 
} 

function renderBox(){ 
    console.log('>>renderBox'); 
    var localRectangle = new Rectangle (10,10,200,50); 
    var stringifiedRectangle = JSON.stringify(localRectangle); 
    var jsonRectangle = JSON.parse(stringifiedRectangle); 
    var svgContainer = d3.select ('#svgPlaceholder').append ("svg") 
     .attr ("width", '250') 
     .attr ("height", '100') 
     .attr ("id", "svgContainer"); 
    var g = svgContainer.append("g") 
     .attr("id","svgBox"); 
    var rectangles = g.selectAll ("rect") 
     .data (jsonRectangle) 
     .enter() 
     .append ("rect"); 

    var rectangleAttributes = rectangles 
     .attr ("x", function (d) { 
      return d.x_axis; 
     }) 
     .attr ("y", function (d) { 
      return d.y_axis; 
     }) 
     .attr ("height", function (d) { 
      return d.height; 
     }) 
     .attr ("width", function (d) { 
      return d.width; 
     }) 
     .style("stroke", "black"); 

} 

renderBox(); 
renderLine(); 

文件so_rect.html:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Title</title> 

</head> 
<body> 

<div class="content" id="svgPlaceholder">Put box here</div> 
<script type="text/javascript" src="d3.js"></script> 
<script type="text/javascript" src="so_rect.js"></script> 
</body> 
</html> 
+0

maye this one help:http://stackoverflow.com/questions/39927308/how-to-draw-a-rectangle-with-d3-js-based-on-2-diametrical-points-and-no-长度-O/39927309#39927309 – Hafenkranich

回答

2

代替:

var lines = g.selectAll("line") 
     .data(jsonLine) 

数据预计JSON数组。

var lines = g.selectAll("line") 
    .data([jsonLine]) //array of line objects 
    .enter() 

同样为矩形

代替

var rectangles = g.selectAll ("rect") 
    .data (jsonRectangle) 

传递JSON数据的一个这样的数组:

var rectangles = g.selectAll ("rect") 
    .data ([jsonRectangle]) //array of json array rectangle. 

工作码here

希望第是有帮助的!