Reputation: 9814
I am trying to draw a rectangle and horizontal line below it. As it is nothing is being drawn and I can't work out why. I'd like to keep the basic structure (separate functions for rectangle and line drawing) if possible as I am drawing multiple rectangles and lines of different sizes/lengths. I'm new to d3.js (and js in general) so any improvements are welcome.
file 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();
file 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>
Upvotes: 1
Views: 1579
Reputation: 32327
Instead of:
var lines = g.selectAll("line")
.data(jsonLine)
Data expects a json array.
var lines = g.selectAll("line")
.data([jsonLine]) //array of line objects
.enter()
Same for rectangles
Instead of
var rectangles = g.selectAll ("rect")
.data (jsonRectangle)
pass an array of json data like this:
var rectangles = g.selectAll ("rect")
.data ([jsonRectangle]) //array of json array rectangle.
Working code here
Hope this helps!
Upvotes: 2