根据 D3 文档,可以为 hull 方法分配自定义访问器来获取 x 和 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");
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/
关于javascript - 具有自定义访问器的 D3 geom.hull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21092006/