天天看點

d3常用API及使用心得

1、記得用svg标簽包裹元素,否則檢視元素屬性都正确,顯示卻是一片空白。

2、應該使用第一種寫法,第二種寫法會導緻不居中顯示,整個圖在左上角。

let svg = d3.select("#basic-topo");
let clientRect = svg.node().getBoundingClientRect(),
    width = +clientRect.width,
    height = +clientRect.height;
           
let svg = d3.select("#basic-topo"),  
    width = +svg.attr("width"),  // 第二種寫法
    height = +svg.attr("height");
           

第三種寫法,用類來封裝

let TopologyGraphLayout = function(vm, selector) {
  var self = this;
  this.vm = vm;

  this.width = $(selector).width();
  this.height = $(selector).height();
    
  this.zoom = d3.zoom().on("zoom", this.zoomed.bind(this)); // 監聽縮放事件
  this.svg = d3
    .select(selector)
    .append("svg")
    .attr("width", this.width)
    .attr("height", this.height)
    .call(this.zoom)
    .on("dblclick.zoom", null);
}
           

3、ID選擇器不要使用".",否則在使用 selection.select 時會報錯

d3常用API及使用心得
在CSS的命名規範中,名稱不能以數字開始,隻能以字母、連字元、下劃線開始。之後可以是字母、連字元、下劃線或數字。      

4、将對象轉為數組的方法

  • d3.keys - 列舉關聯數組的鍵。
  • d3.values - 列舉關聯數組的值。
  • d3.entries - 列舉關聯數組的鍵值對實體。

5、映射

  • d3.map - 建立一個空的map。
  • map.has - 傳回map中是否包含某個值。
  • map.get - 擷取值。
  • map.set - 設定值。
  • map.remove - 移除值。
  • map.clear - 移除所有值。
  • map.keys - 擷取鍵數組。
  • map.values - 擷取值數組。
  • map.entries - 擷取鍵值對數組。
  • map.each - 為每個元素調用一次指定的方法。
  • map.empty - 傳回map是否為空。
  • map.size - 計算值的數量。

6、集合

  • d3.set - 建立一個空的set。
  • set.has - 傳回set中是否包含某個值。
  • set.add - 添加指定值。
  • set.remove - 删除指定值。
  • set.clear - 移除所有值。
  • set.values - 擷取值數組。
  • set.each - 為每個元素調用一次指定的方法。
  • set.empty - 傳回set是否為空。
  • set.size - 計算值的數量。

7、選擇元素

d3選擇,插入, 删除元素

  • d3.selection - 選擇根文檔元素。
  • d3.select - 從文檔中選擇一個元素。
  • d3.selectAll - 從文檔中選擇多個元素。
  • selection.select - 選擇每個選中元素的一個後代元素。
  • selection.selectAll - 選擇每個選中元素的多個後代元素。
  • selection.filter - 基于資料過濾元素。
  • selection.merge - 合并兩個選擇。
  • d3.matcher - 測試一個元素是否比對選擇器。
  • d3.selector - 選擇一個元素。
  • d3.selectorAll - 選擇多個元素。
  • d3.window - 得到節點的所有者視窗。

8、修改元素

  • selection.attr - 設定或擷取特性。
  • selection.classed - 擷取,添加或移除CSS類。
  • selection.style - 設定或擷取樣式。
  • selection.property - 設定或擷取行内屬性。
  • selection.text - 設定或擷取文本内容。
  • selection.html - 設定或擷取inner HTML。
  • selection.append - 建立,添加或選擇新的元素。
  • selection.remove - 移除文檔中的元素。
  • selection.sort - 基于資料給文檔中的元素排序。
  • selection.order - 重排列文檔中的元素以比對選擇中的順序。
  • selection.raise - 重新排列每個元素為父元素的最後一個子節點。
  • selection.lower - 重新排列每個元素為父元素的第一個子節點。
  • d3.creator - 通過名稱建立元素。

9、資料綁定

了解update,enter,exit的使用

  • selection.data - 元素和資料綁定。
  • selection.enter - 獲得進入(enter)選擇器(資料無元素)。
  • selection.exit - 獲得退出(exit)選擇器(元素無資料)。
  • selection.datum - 擷取或設定元素的資料(不綁定)。