Peterson Peterson - 25 days ago 5
Javascript Question

Multiple ellipses in D3 not visible with no error

A simple program for multiple ellipse I have written. The program shows no error but also no ellipse is being seen. Though i tried add multiple random colors for it. I think there is some slight mistake somewhere. 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 customData = [
{ "x": 30, "y": 30, "width": 20, "height" : 10 },
{ "x": 70, "y": 70, "width": 20, "height" : 20},
{ "x": 110, "y": 100, "width": 20, "height" : 30}
];

//Make an SVG Container
var mySVG = d3.select("svg");

//create ellipses skeleton by data
var ellipses = mySVG.selectAll("ellipse")
.data(customData)
.enter()
.append("ellipse");

//Draw the Rectangle
ellipses.append("ellipse")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("rx", function (d) { return d.width; })
.attr("ry", function(d) { return d.height; })
.attr("fill",function() { return "hsl(" + Math.random() * 360 + ",100%,50%)"; });

});

</script>
</head>
<body>
<svg width="500px" height="500px"></svg>
</body>
</html>

Answer

You are appending ellipse elements twice. Here is the working snippet.

var customData = [{
  "x": 30,
  "y": 30,
  "width": 20,
  "height": 10
}, {
  "x": 70,
  "y": 70,
  "width": 20,
  "height": 20
}, {
  "x": 110,
  "y": 100,
  "width": 20,
  "height": 30
}];

//Make an SVG Container
var mySVG = d3.select("svg");

//create ellipses skeleton by data  
var ellipses = mySVG.selectAll("ellipse")
  .data(customData)
  .enter()
  .append("ellipse");

// Removed second append from here

//Draw the Rectangle
ellipses.attr("cx", function(d) {
    return d.x;
  })
  .attr("cy", function(d) {
    return d.y;
  })
  .attr("rx", function(d) {
    return d.width;
  })
  .attr("ry", function(d) {
    return d.height;
  })
  .attr("fill", function() {
    return "hsl(" + Math.random() * 360 + ",100%,50%)";
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500px" height="500px"></svg>

Comments