D3.js入門之D3?DataJoin的使用
DataJoin(數(shù)據(jù)連接)是D3中很重要的一個概念。上一章有提到D3是基于數(shù)據(jù)操作DOM的js庫,DataJoin使我們能夠根據(jù)現(xiàn)有 HTML 文檔中的數(shù)據(jù)集注入、修改和刪除元素。
上一章中我們用forEach循環(huán)的方式,畫了三個圓,那么在D3中該怎樣優(yōu)雅的處理呢?
const circles = [
{ text: 1, color: "red" },
{ text: 2, color: "green" },
{ text: 3, color: "blue" }
];
svg.selectAll("circle")
.data(circles) // 綁定數(shù)據(jù)
.enter() // 獲取有數(shù)據(jù)沒dom的集合
.append("circle")
.attr("class", "circle")
.attr("id", (d) => `circle${d.text}`) // d 表示 data綁定的數(shù)據(jù)中的一項
.attr("cx", (d) => 50 * d.text)
.attr("cy", 50)
.attr("r", 20)
.attr("fill", (d) => d.color);
data、enter、exit
- data 將指定數(shù)組的數(shù)據(jù) data 與已經(jīng)選中的元素進行綁定并返回一個新的選擇集和enter 和 exit
- enter 返回選擇集中有數(shù)據(jù)但沒有對應(yīng)的DOM元素
- exit 選擇集中有DOM元素但沒有對應(yīng)的數(shù)據(jù)

<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返回的是有數(shù)據(jù)沒有dom的集合,也就是數(shù)據(jù)比dom多,所以enter和append基本上都是成對出現(xiàn)的。
d3.select("#dataEnter")
.selectAll("p")
.data(arr)
.enter()
.append("p")
.text((d) => d);

exit返回的是有dom沒有數(shù)據(jù)的集合,也就是dom比數(shù)據(jù)多,所以exit和remove基本上也是成對出現(xiàn)的。
const arr = [1,2,3]
d3.select("#dataEnter")
.selectAll("p")
.data(arr)
.text((d) => d)
.exit()
.remove();


datum
如果datum()綁定的值是數(shù)組,那么整個數(shù)組會綁定到每個被選擇的元素上。
而使用data()的話,那么會依次綁定數(shù)據(jù)。
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 根據(jù)需要追加、刪除和重新排列元素,以匹配先前通過選擇綁定的數(shù)據(jù),返回合并后的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");

最后
這里有一個示例動態(tài)的顯示了enter(綠色)、update(灰色)、exit(紅色)效果:

以上就是D3.js入門之D3 DataJoin的使用的詳細內(nèi)容,更多關(guān)于D3.js DataJoin的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
由JavaScript技術(shù)實現(xiàn)的web小游戲(不含網(wǎng)游)
伴隨Ajax與網(wǎng)頁游戲的崛起,曾幾何時JavaScript也成了游戲開發(fā)時可供選擇的技術(shù)之一,文本 僅列舉數(shù)項由JavaScript技術(shù)實現(xiàn)的web小游戲(不含網(wǎng)游),聊作參考之用。2010-06-06
VS?Code中搭建JavaScript運行環(huán)境超詳細過程
這篇文章主要介紹了JavaScript從瀏覽器到服務(wù)端的演變,以及如何在VSCode中安裝和配置Node.js和相關(guān)插件來運行JavaScript代碼,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2025-04-04

