iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >D3.js入门之D3 DataJoin的使用
  • 648
分享到

D3.js入门之D3 DataJoin的使用

D3.js DataJoin使用D3.js DataJoinD3 DataJoin 2022-11-13 19:11:01 648人浏览 独家记忆
摘要

目录data、enter、exitdatumjoin最后DataJoin(数据连接)是D3中很重要的一个概念。上一章有提到D3是基于数据操作DOM的js库,DataJoin使我们能够

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 示例

以上就是D3.js入门之D3 DataJoin的使用的详细内容,更多关于D3.js DataJoin的资料请关注编程网其它相关文章!

--结束END--

本文标题: D3.js入门之D3 DataJoin的使用

本文链接: https://www.lsjlt.com/news/170973.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作