Peterson Peterson - 23 days ago 8
Javascript Question

Making multiple rectangles in SVG by D3 error

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; })


enter image description here

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.

Answer

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...).

Comments