Reputation: 8240
In example I am making 3 rectangles based on custom data. I should have got my 3 rectangles but still getting error. 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.
Upvotes: 0
Views: 1021
Reputation: 140
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
Upvotes: 1
Reputation: 102219
You have to use your recently created rect
variable, which contains your "enter" selection:
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 d.x
, d.y
etc...).
Upvotes: 1