Javascript d3js绘制svg矩形和线条问题
我试着在它下面画一个矩形和水平线。因为没有什么东西被画出来,我不知道为什么。如果可能的话,我希望保留基本结构(矩形和线条的单独功能),因为我正在绘制多个不同大小/长度的矩形和线条。我对d3.js(和一般的js)是新手,所以欢迎任何改进 文件so_rect.js:Javascript d3js绘制svg矩形和线条问题,javascript,d3.js,svg,Javascript,D3.js,Svg,我试着在它下面画一个矩形和水平线。因为没有什么东西被画出来,我不知道为什么。如果可能的话,我希望保留基本结构(矩形和线条的单独功能),因为我正在绘制多个不同大小/长度的矩形和线条。我对d3.js(和一般的js)是新手,所以欢迎任何改进 文件so_rect.js: function Rectangle(x, y, height, width) { this.x_axis = x; this.y_axis = y; this.height = height; this
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>
标题
把箱子放在这里
而不是:
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.
工作代码
希望这有帮助 maybee这个有帮助: