带有自定义访问器的D3 geom.hull

时间:2014-01-13 13:02:55

标签: javascript svg d3.js convex-hull

根据D3文档,可以为船体方法分配自定义访问器以获取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.

1 个答案:

答案 0 :(得分: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/