我正在尝试在它下方绘制一个矩形和水平线。因为它没有被吸引,我无法解决原因。如果可能的话,我想保留基本结构(矩形和线条图的单独功能),因为我绘制了多个不同大小/长度的矩形和线条。我是d3.js(以及一般的js)的新手,所以欢迎任何改进。
文件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 :(得分: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
希望这有帮助!