d3.js - v3 and v4 - Enter and Update differences

后端 未结 2 1279
长发绾君心
长发绾君心 2020-11-28 16:37

I\'m trying to get the values for x and y to make a circles using d3.js v4. With the following code I manage to create the chart like behavior of t

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 17:16

    Update pattern was changed in d3v4. Excerpt from the documentation:

    In addition, selection.append no longer merges entering nodes into the update selection; use selection.merge to combine enter and update after a data join.

    You should rewrite your code this way:

    var svg = d3.select('body').append('svg')
                .attr('width', 250)
                .attr('height', 250);
    
        //render the data
        function render(data){
                //Bind 
                var circles = svg.selectAll('circle').data(data);
    
                //Enter
                circles.enter().append('circle')
                    .attr('r', 10).merge(circles) // <== !!!
                    .attr('cx', function(d) { return d.x; })
                    .attr('cy', function(d) { return d.y; });
    
    
                //Exit
                circles.exit().remove();
        }
    
       
    
        var myObjects = [
            {x: 100, y: 100},
            {x: 130, y: 120},
            {x: 80, y: 180},
            {x: 180, y: 80},
            {x: 180, y: 40}
        ];
        
    
        render(myObjects);

提交回复
热议问题