Basic D3 API to Manipulate DOM

Preface


Intro of D3.js


Common Flow of Drawing using D3.js API

  1. d3.select() 輸入 css selector 決定圖表的位置
    • 回傳 selection,供之後使用
    • selection 是個 array,裏面裝 array of elements,以及 parentNode 資訊
  2. selection.data(myArr[, key])myArrselection 接在一起
    • myArr 資料放在 DOM Node 的屬性 __data__
    • 回傳 update-selection, 之後就可以呼叫 .enter()
    • key 是個函式,可以客制化要連結的陣列元素的屬性
    • 如果圖表位置沒有子元素要先用 .selectAll() 再呼叫 .data()
  3. selection.enter() 選擇 沒有與 HTML 元素連結的資料
    • 回傳 enter-selection
    • 只有 enter-selection 才可以呼叫 .append().insert()
  4. selection.append()enter-selection 建立新 HTML 元素

  5. update-selection 呼叫 .exit().remove()
    • 選擇 沒有和資料連結的 HTML 元素 並移除
    • 官方文件解釋 exit() 的用法
    • enter() 對比 exit()
      • 「沒有與 HTML 元素連結的資料」與「沒有和資料連結的 HTML 元素」
  6. selection.text() 遍歷 update-selection 為元素建立文字

  7. selection.style() 遍歷 update-selection 設定元素樣式
var myArr = [['John', 'm', 18 ], ['Mary', 'f', 20 ], ['Ivy', 'f', 27 ]]
// name, gender, age

var divSelection = d3.select("body")                   // 1.
                     .selectAll("div")
                     .data(myArr, (e)=>{ return e })   // 2.

divSelection.enter().append("div")        // 3. 4.
divSelection.exit().remove()              // 5.

divSelection.text((e)=>{ return e[0] })   // 6.
            .style({                      // 7.
              margin: "5px",
              "background-color": (e)=>{return (e[1] === 'm')? '#A9D0F5':'#D0A9F5'},
              width: (e)=>{return (e[2]*10)+"px"}  // calculate by age
            })


Summary