[英]Making multiple rectangles in SVG by D3 error
In example I am making 3 rectangles based on custom data. 在示例中,我根据自定义数据制作了3个矩形。 I should have got my 3 rectangles but still getting error.
我应该有3个矩形,但仍然会出错。 Can someone help out?
有人可以帮忙吗?
SNIPPET: 片段:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script>
<script>
$(document).ready(function(){
//our basic data
var rectData = [
{ "x": 30, "y": 30, "width": 20, "height" : 10 },
{ "x": 70, "y": 70, "width": 20, "height" : 20},
{ "x": 110, "y": 100, "width": 20, "height" : 30}
];
//selection of svg
var mySVG = d3.select("svg");
//create rectangle skeleton
var rect = mySVG.selectAll("rect")
.data(rectData)
.enter()
.append("rect");
//Draw the Rectangle
mySVG.append("rect")
.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; })
.attr("width", function (d) { return d.width; })
.style("height", function(d) { return d.height; });
});
</script>
</head>
<body>
<svg width="500px" height="500px"></svg>
</body>
</html>
Error: 错误:
.attr("x", function (d) { return d.x; })
Please, help out in knowing what is the errror in the program and help me create the three rectangles based on the custom data in array. 请帮助您了解程序中的错误,并帮助我根据数组中的自定义数据创建三个矩形。 Thanks in advance.
提前致谢。
You have to use your recently created rect
variable, which contains your "enter" selection: 您必须使用最近创建的
rect
变量,其中包含“输入”选择:
rect.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; })
.attr("width", function (d) { return d.width; })
.style("height", function(d) { return d.height; });
You're getting this error because you're using mySVG
to set the attributes, which is just an SVG selection and has no bound data (hence, no dx
, dy
etc...). 之所以会出现此错误,是因为您正在使用
mySVG
设置属性,这只是SVG选择,没有绑定数据(因此,没有dx
, dy
等。)。
Just combine the following two scripts into one. 只需将以下两个脚本合并为一个。
//create rectangle skeleton
var rect = mySVG.selectAll("rect")
.data(rectData)
.enter()
.append("rect");
//Draw the Rectangle
mySVG.append("rect")
.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; })
.attr("width", function (d) { return d.width; })
.style("height", function(d) { return d.height; });
changes to 更改为
//create rectangle skeletons and draw the rectangles
var rect = mySVG.selectAll("rect")
.data(rectData)
.enter()
.append("rect");
.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; })
.attr("width", function (d) { return d.width; })
.style("height", function(d) { return d.height; });
https://jsfiddle.net/mwf2d1fd/ A JS fiddle https://jsfiddle.net/mwf2d1fd/ JS小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.