根据D3文档,可以为hull方法分配自定义访问器,以获取x和y坐标。
Hull documentation
我想使用这些自定义访问器,但无法弄清楚语法。这就是我所做的,这基本上是一个简单的解决方法,在该方法中,我手动转换了我的vertices
数组。
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和y值,而不必求助于变换数组。
这是一个fiddle.
最佳答案
经过一番尝试后,我得到了代码,并按照我最初想要的方式工作。
设置自定义访问器的关键是:
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/