D3数据可视化-General Update Pattern

D3 是 Data Driven Documents 的简称,意思是数据驱动文档。D3 可以帮助我们自动化地操作 HTML、SVG 或 Canvas 等元素(element),对其进行添加、更新和删除处理。一旦绑定了数据和元素的对应关系之后,文档元素会随着数据的变化自动进行对应改变,这就是数据驱动。

其中添加(enter)、更新(update)和删除(exit)三种操作,我们称为 General Update Pattern。

一般来说,整个数据驱动流程由下面几步组成:

  • 选择所有将要操作的元素。(selection)
  • 绑定数据,使其和元素一一对应。(data binding)
  • 如果一个数据找不到对应的元素,那么添加一个元素。(enter)
  • 根据目前的数据对绑定的元素更新属性。(update)
  • 删除没有对应数据的元素。(exit)
update-pattern.gif

上面这个例子演示了数据的变化过程,绿色的柱子代表了新加入的元素,红的的柱子代表将要移除的元素,灰色的柱子代表更新了位置的柱子。

选择所有 rect 元素,绑定数组数据。

const bar = svg.selectAll('rect').data(data, (d) => d);

移除没有对应数据的元素,加特效。

bar.exit()
  .attr('class', 'exit')
  .transition(t)
  .attr('y', (d) => maxHeight - barHeight(d) + 60)
  .style('fill-opacity', 1e-6)
  .remove();

更新现存元素,移动位置。

bar.attr('class', 'update')
  .attr('y', (d, i) => {
    const height = barHeight(d);
    return maxHeight - height;
  })
  .attr('width', barWidth - 1)
  .attr('height', (d) => barHeight(d))
  .style('fill-opacity', 1)
  .transition(t)
  .attr('x', (d, i) => barWidth * i)

添加新的元素,加特效。

bar.enter()
  .append('rect')
  .attr('class', 'enter')
  .attr('width', barWidth - 1)
  .attr('height', (d) => barHeight(d))
  .attr('x', (d, i) => barWidth * i)
  .attr('y', (d) => maxHeight - barHeight(d) - 60)
  .style('fill-opacity', 1e-6)
  .transition(t)
  .attr('y', (d, i) => {
    const height = barHeight(d);
    return maxHeight - height;
  })
 .style('fill-opacity', 1)

这里的特效很简单,一开始给定一个初始样式(style),经过一段时间的变化(duration),到达结束状态(style)。如果没有指定开始样式,D3 会通过 getComputedStyle 来获取。

完整源码在这里

你可能感兴趣的:(D3数据可视化-General Update Pattern)