美文网首页
three little circle

three little circle

作者: 雷朝建 | 来源:发表于2019-03-09 17:29 被阅读0次
<svg style={{ width: 720, height: 120 }}>
  <circle cx="40" cy="60" r="10"></circle>
  <circle cx="80" cy="60" r="10"></circle>
  <circle cx="120" cy="60" r="10"></circle>
</svg>
1.png

选择元素

  • 使用selectAll/select来选择元素.
  • 可以使用style/attr来设置元素属性.
const circle = d3.selectAll('circle');
circle.style('fill', 'steelblue').attr('r', 30)
  .attr('cx', () => Math.random() * 720);

绑定数据

  • 使用data方法来绑定数据.
  • 绑定数据后, 每个属性的方法第一个参数对应数据的元素, 第二个参数对应索引.
const data = [32, 57, 112];
const circle = d3.selectAll('circle');
circle.data(data).style('fill', 'steelblue').attr('r', (d, i) => i + Math.sqrt(d));
2.PNG

新建元素

  • 使用enter属性来新建元素.
const svg = d3.select("svg");
svg.selectAll("circle").data([32, 57, 112, 293])
  .enter().append("circle")
  .attrs({ cx: (d, i) => i * 100 + 30, cy: 60, r: d => Math.sqrt(d)});
  • circle最早是没有的, 但是我们可以先selectAll, 然后enter后append("circle"), 这样circle就动态生成了.
  • 安装d3-selection-multi, 就可以使用attrs属性.


    3.PNG

删除元素

  • 使用exit来保留提供数据的元素. 如果执行remove, 则删除没提供数据的剩余元素.
const svg = d3.select("svg");
svg.selectAll("circle").data([32, 57, 112, 293])
  .enter().append("circle")
  .attrs({ cx: (d, i) => i * 100 + 30, cy: 60, r: d => Math.sqrt(d)});

svg.selectAll("circle").data([32, 57])
  .exit().remove();
  • 这样32, 57对应的元素就保留下来, 112, 293对应的元素则被删除.

相关文章

网友评论

      本文标题:three little circle

      本文链接:https://www.haomeiwen.com/subject/ltbtpqtx.html