D3.js--从陌生到熟悉

General Update Pattern

2018-04-21  本文已影响0人  雷朝建

导航

这篇文章由四部分组成.

第一部分

主要代码如下:

    const update = (data) => {
      const text = g.selectAll('text').data(data);
      text.attr('class', 'update');

      text.enter().append('text')
        .attr('class', 'enter')
        .attr('x', (d, i) => i * 32)
        .attr('dy', '.35em')
        .merge(text)
        .text(d => d);
      
      text.exit().remove();
    }

第二部分

主要代码如下:

    const update = (data) => {
      const text = g.selectAll('text').data(data, d => d);
      text.attr('class', 'update');

      text.enter().append('text')
        .attr('class', 'enter')
        .attr('dy', '.35em')
        .merge(text)
        .attr('x', (d, i) => i * 32)
        .text(d => d);

      text.exit().remove();
    }

相比于第一部分,这里做了两处修改:

第三部分

主要代码如下:

    const update = (data) => {
      const text = g.selectAll('text').data(data, d => d);
      const t = d3.transition().duration(750);

      text.exit()
        .attr('class', 'exit')
        .transition(t)
        .attr('y', 60)
        .style('fill-opacity', 1e-6)
        .remove();

      text.attr('class', 'update')
        .attr('y', 0)
        .style('fill-opacity', 1)
        .transition(t)
        .attr('x', (d, i) => i * 32);

      text.enter().append('text')
        .attr('class', 'enter')
        .attr('y', -60)
        .attr('x', (d, i) => i * 32)
        .style('fill-opacity', 1e-6)
        .text(d => d)
        .transition(t)
        .attr('y', 0)
        .style('fill-opacity', 1);
    }

第四部分

设置文本位置代码:

text.enter().append('text')
      .attr('fill', 'green').attr('dy', '.35em')
      .style('font', 'bold 48px monospace')
      .attr('y', 0)
      .attr('x', (d, i) => i * 32)
      .text(d => d)
      .attr('class', d => `key-${d}`)

监听键盘事件代码:

  keyDown = (e) => {
    const alphabet = this.state.alphabet;
    const key = alphabet[e.keyCode - 65];
    const t = d3.transition().duration(2000);
    d3.select(`.key-${key}`)
      .transition(t)
      .attr('y', -250)
      .style('fill-opacity', 1e-6)
      .transition(t)
      .attr('y', 0)
      .style('fill-opacity', 1);
  }

源码位置

上一篇 下一篇

猜你喜欢

热点阅读