javascript - 具有自定义访问器的 D3 geom.hull

标签 javascript svg d3.js convex-hull

根据 D3 文档,可以为 hull 方法分配自定义访问器来获取 x 和 y 坐标。

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 + ")";});
}

我想要一个能够直接使用顶点数组的 xy 值的示例,而不必求助于转换我的数组。

这是一个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/

相关文章:

javascript - 正确更新 D3 饼图

javascript - 如何使用 d3 获取 map 以准确显示经度和纬度

javascript - 在正则表达式中转义变量

javascript - new Array(length) 给出了错误的大小

javascript - Vue 过滤器函数总是返回 5 个以上的元素

javascript - 如何使用 Snap.svg 操作现有的组元素

javascript - 带有子值指示器和标签的仪表图

php - PHP中的 bool 变量值到javascript实现

javascript - 覆盖不同页面上的javascript函数

html - 用于 ie 的 css mask-image 替代品,用于创建可编辑的 svg 背景颜色