D3.js入门之D3 DataJoin的使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

D3.js入门之D3 DataJoin的使用

FinGet   2022-11-09 我要评论

DataJoin(数据连接)是D3中很重要的一个概念。上一章有提到D3是基于数据操作DOM的js库,DataJoin使我们能够根据现有 HTML 文档中的数据集注入、修改和删除元素。

上一章中我们用forEach循环的方式,画了三个圆,那么在D3中该怎样优雅的处理呢?

const circles = [
    { text: 1, color: "red" },
    { text: 2, color: "green" },
    { text: 3, color: "blue" }
];

svg.selectAll("circle")
    .data(circles) // 绑定数据
    .enter() // 获取有数据没dom的集合
    .append("circle")
    .attr("class", "circle")
    .attr("id", (d) => `circle${d.text}`) // d 表示 data绑定的数据中的一项
    .attr("cx", (d) => 50 * d.text)
    .attr("cy", 50)
    .attr("r", 20)
    .attr("fill", (d) => d.color);

data、enter、exit

  • data 将指定数组的数据 data 与已经选中的元素进行绑定并返回一个新的选择集和enter 和 exit
  • enter 返回选择集中有数据但没有对应的DOM元素
  • exit 选择集中有DOM元素但没有对应的数据

<div id="dataEnter">
    <p></p>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
</div>
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const update = d3.select("#dataEnter")
  .selectAll("p")
  .data(arr)
  .text((d) => d);

因为有5个p标签,所以从1开始渲染到5。

enter返回的是有数据没有dom的集合,也就是数据比dom多,所以enterappend基本上都是成对出现的。

d3.select("#dataEnter")
  .selectAll("p")
  .data(arr)
  .enter()
  .append("p")
  .text((d) => d);

exit返回的是有dom没有数据的集合,也就是dom比数据多,所以exitremove基本上也是成对出现的。

const arr = [1,2,3]

d3.select("#dataEnter")
  .selectAll("p")
  .data(arr)
  .text((d) => d)
  .exit()
  .remove();

点击查看data, enter, exit示例

datum

如果datum()绑定的值是数组,那么整个数组会绑定到每个被选择的元素上。

而使用data()的话,那么会依次绑定数据。

const datumDom = d3.select("#datum")
    .selectAll("p")
    .datum(circles)
    .text((d) => {
        console.log(d);
        return JSON.stringify(d);
    });

selection.datum().append()如果选择集是空的,那么并不会添加元素,所以使用datum要确保选择项(dom)存在。实际项目中,图表都是从0到1绘制,所以一般都是使用data().append()

join

const arr = [1, 2, 3];

svg.selectAll("circle")
    .data(arr)
    .join("circle")
    .attr("cx", (d) => d * 50)
    .attr("cy", (d) => d * 50)
    .attr("r", 16)
    .attr("fill", "#F89301");

join 根据需要追加、删除和重新排列元素,以匹配先前通过选择绑定的数据,返回合并后的enter和update集合。

也就是说join是一个简化操作,我们可以把join分解一下:

const circle = svg.selectAll("circle").data(arr);

const newCircle = circle.enter()
    .append("circle")
    .merge(circle)
    .attr("cx", (d) => d * 50)
    .attr("cy", (d) => d * 50)
    .attr("r", 16)
    .attr("fill", "#F89301");

最后

这里有一个示例动态的显示了enter(绿色)update(灰色)exit(红色)效果:

点击查看 join 示例

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们