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ù)但沒有對應的DOM元素
- exit 選擇集中有DOM元素但沒有對應的數(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)容,更多關于D3.js DataJoin的資料請關注腳本之家其它相關文章!
相關文章
js實現(xiàn)json數(shù)據(jù)行到列的轉(zhuǎn)換的實例代碼
為了實現(xiàn)這樣的數(shù)據(jù)顯示出來三個序列,分別為鄭州、新鄉(xiāng)、安陽的電量,就需要自己實現(xiàn)對這樣數(shù)據(jù)的轉(zhuǎn)換,轉(zhuǎn)換成如下的形式:2013-08-08
JS實現(xiàn)的駝峰式和連字符式轉(zhuǎn)換功能分析
這篇文章主要介紹了JS實現(xiàn)的駝峰式和連字符式轉(zhuǎn)換功能,結(jié)合實例形式分析了JS實現(xiàn)字符串的駝峰式與連接符式轉(zhuǎn)換的實現(xiàn)技巧,涉及js字符串遍歷、轉(zhuǎn)換及正則表達式相關操作方法,需要的朋友可以參考下2016-12-12

