d3.js在v4中设置属性

时间:2016-11-22 16:42:45

标签: javascript d3.js

以下代码适用于D3 v3 ,但不适用于 v4

function render(data) {
  //bind
  var cirs = svg.selectAll('circle').data(data);

  //enter
  cirs.enter().append('circle').attr('r', 2);

  //update
  cirs.attr('cx', function(d) {
    return d.x
  })
  .attr('cy', function(d) {
    return d.y
  });

  //exit
  cirs.exit().remove();
}

我的数据:

var objects = [
  {x: 100, y:100},
  {x: 70, y: 90},
  {x: 181, y: 105},
  {x: 80, y: 60},
  {x: 160, y: 120},
  {x: 168, y: 182},
  {x: 95, y: 110}
]
render(objects);

我发现cxcy未设置。

是否有一种在版本4中设置属性的新方法?

1 个答案:

答案 0 :(得分:2)

v4的changelog有答案:

  

此外,selection.append不再将输入节点合并到更新选择中;在数据加入后使用selection.merge组合输入和更新。

因此,您的更新选择将为空,并且永远不会执行对.attr()的调用,从而导致缺少属性值。

要使代码生效,您只需将之前输入的圈子合并到更新选择中:

function render(data) {
  //bind
  var cirs = svg.selectAll('circle').data(data);

  //enter
  var enter = cirs.enter().append('circle').attr('r', 2);

  //update (including merged enter selection)
  var update = cirs.merge(enter); // Merge the enter selection into the update selection
  update.attr('cx', function(d) {
      return d.x
    })
    .attr('cy', function(d) {
      return d.y
    });

  //exit
  cirs.exit().remove();
}

var svg = d3.select('body').append('svg')
  .attr('width', 250)
  .attr('height', 250);

function render(data) {
  //bind
  var cirs = svg.selectAll('circle').data(data);

  //enter
  var enter = cirs.enter().append('circle').attr('r', 2);

  //update (including merged enter selection)
  var update = cirs.merge(enter); // Merge the enter selection into the update selection
  update.attr('cx', function(d) {
      return d.x
    })
    .attr('cy', function(d) {
      return d.y
    });

  //exit
  cirs.exit().remove();
}

var objects = [{
  x: 100,
  y: 100
}, {
  x: 70,
  y: 90
}, {
  x: 181,
  y: 105
}, {
  x: 80,
  y: 60
}, {
  x: 160,
  y: 120
}, {
  x: 168,
  y: 182
}, {
  x: 95,
  y: 110
}];

render(objects);
<script src="https://d3js.org/d3.v4.js"></script>

相关问题