javascript - d3 skips first index in an array when appending circles -


i'm new using d3 , i'm trying evenly place circles around circle dividing n pieces. problem not draw first circle though coords[0] exists. instead places starts @ coords[1] , continues. reason why , how fix it?

main.html

<!doctype html> <html>     <head>         <title>a circle</title>         <meta charset="utf-8" />         <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>         <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.16.1/math.min.js"></script>     </head>     <body>         <script type="text/javascript" src="circle.js"></script>     </body> </html> 

circle.js

    var w = 500;     var h = 500;     var n = 10;     var r = h/2-20;     var coords = [];      (var = 0; i<n; i++)     {         var p_i = {};         p_i.x = w/2+r*math.cos((2*math.pi/n)*i);         p_i.y = h/2-r*math.sin((2*math.pi/n)*i);         coords.push(p_i);     }       var svg = d3.select('body') //svg canvas         .append('svg')         .attr('width', w)         .attr('height', h);      var circle = svg.append('circle') //draw big circle         .attr('cx', w/2)         .attr('cy', h/2)         .attr('r', r)         .attr('fill', 'teal')         .attr('stroke', 'black')         .attr('stroke-width', w/100);      var center = svg.append('circle') //construct center         .attr('cx', w/2)         .attr('cy', h/2)         .attr('r', r/50)         .attr('fill', 'red')         .attr('stroke', 'black')         .attr('stroke-width', w/100);      var approx_pts = svg.selectall('circle')         .data(coords, function(d)               {                   return this.id;               })         .enter()         .append('circle')         .attr('cx', function(d)               {                   return d.x;               })         .attr('cy', function(d)               {                   return d.y;               })         .attr('r', w/100)         .attr('fill', 'black'); 

you have circles in svg when this:

var approx_pts = svg.selectall('circle') 

therefore, "enter" selection has less elements data array.

solution: use selectall(null):

var approx_pts = svg.selectall(null) 

that way can sure enter selection has elements in data array. of course, approach avoids creating "update" , "exit" selections in future.

if plan use "update" , "exit" selections, can select class:

var approx_pts = svg.selectall(".mycircles") 

don't forget set class when append circles in enter selection, of course.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -