Reputation: 63
I am trying to draw two circles using D3 and by appending SVG. The code provided below is not producing desired result. It draws the first green circle but not the next one. Please help me to understand what is wrong with the code provided below ...
<!DOCTYPE HTML>
<html>
<head>
<title>Selection Method
</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script>
d3.select("body")
.append("svg")
.attr("width", 960)
.attr("height", 500)
.style('background', '#dff0d8')
.append("g")
.attr("transform", "translate(0,0)")
.append("circle")
.attr("cx", 20)
.attr("cy", 20)
.attr("r", 10)
.attr("fill", "green")
.append("circle")
.attr("cx", 70)
.attr("cy", 70)
.attr("r", 10)
.attr("fill", "black")
</script>
</body>
Upvotes: 0
Views: 450
Reputation: 1157
Your code attempts to append a second circle
to the first circle
. Simply "outdenting" the code doesn't change the scope.
Here is a trivial change that draws what you likely expect:
d3.select("body")
.append("svg")
.attr("width", 960)
.attr("height", 500)
.style('background', '#dff0d8')
.append("g")
.attr("transform", "translate(0,0)")
.append("circle")
.attr("cx", 20)
.attr("cy", 20)
.attr("r", 10)
.attr("fill", "green")
d3.select('g') // <- Note the reselection of the existing 'g' element
.append("circle")
.attr("cx", 70)
.attr("cy", 70)
.attr("r", 10)
.attr("fill", "black")
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
Upvotes: 2