2014-01-13 53 views
1

根據D3文檔,可以爲船體方法分配自定義訪問器以獲取x和y座標。D3 geom.hull with custom accessors

Hull documentation

我想用這些自定義訪問器,但我想不通的語法。這是我所做的,這基本上是一個不起眼的解決方法,我手動轉換數組。

var width = 900, 
    height = 600; 

var svg = d3.select("#content").append("svg") 
     .attr("width", width) 
     .attr("height", height); 

var hull = svg.append("path") 
       .attr("class", "hull"); 

var circle = svg.selectAll("circle"); 

var vertices = [{"keyWord" : "key", "x" : 10, "y" : 20}, 
      {"keyWord" : "key1", "x" : 0, "y" : 10}, 
      {"keyWord" : "key2", "x" : 100, "y" : 25}, 
      {"keyWord" : "key3", "x" : 80, "y" : 50}, 
      {"keyWord" : "key4", "x" : 15, "y" : 35}, 
      {"keyWord" : "key4", "x" : 500, "y" : 500}, 
]; 

test = []; 

vertices.forEach(function(node){ 
    test.push([node.x, node.y]); 
}); 

redraw(); 

function redraw(){ 
    hull.datum(d3.geom.hull(test)).attr("d", function(d) { return "M" + d.join("L") + "Z"; }); 
    circle = circle.data(vertices); 
    circle.enter().append("circle").attr("r", 3); 
    circle.attr("transform", function(d){ return "translate(" + d + ")";}); 
} 

我想一個例子可以使用我的頂點數組的Xÿ值,而不是直接不必訴諸改造我的數組。

這裏有一個fiddle.

回答

1

試圖一點點我的代碼工作,我想它最初的方式後。

來設置自定義訪問器的關鍵是:

var customHull = d3.geom.hull(); 
customHull.x(function(d){return d.x;}); 
customHull.y(function(d){return d.y;}); 

這裏是整個代碼:

var width = 900, 
    height = 600; 

var svg = d3.select("#content").append("svg") 
     .attr("width", width) 
     .attr("height", height); 

var hull = svg.append("path") 
       .attr("class", "hull"); 

var circle = svg.selectAll("circle"); 

vertices = [{"keyWord" : "key", "x" : 10, "y" : 20}, 
      {"keyWord" : "key1", "x" : 0, "y" : 10}, 
      {"keyWord" : "key2", "x" : 100, "y" : 25}, 
      {"keyWord" : "key3", "x" : 80, "y" : 50}, 
      {"keyWord" : "key4", "x" : 15, "y" : 35}, 
      {"keyWord" : "key5", "x" : 500, "y" : 500}, 
]; 

var customHull = d3.geom.hull(); 
customHull.x(function(d){return d.x;}); 
customHull.y(function(d){return d.y;}); 

redraw(); 

function redraw(){ 
    hull.datum(customHull(vertices)).attr("d", function(d) { console.log(d); return "M" + d.map(function(n){ return [n.x, n.y] }).join("L") + "Z"; }); 
    circle = circle.data(vertices); 
    circle.enter().append("circle").attr("r", 3); 
    circle.attr("transform", function(d){ return "translate(" + d + ")";}); 
} 

而且的jsfiddle http://jsfiddle.net/udvaritibor/3YC5C/1/

相關問題