【问题标题】:Create Unique Path Within Each SVG Group Element Using D3使用 D3 在每个 SVG 组元素中创建唯一路径
【发布时间】:2015-07-13 15:47:12
【问题描述】:

我正在尝试创建 50 个 SVG 组,每个组都包含绘制特定美国州的路径。但是,在为该组创建状态路径时,我无法弄清楚如何从 SVG 组访问状态数据。有人可以让我走上正轨吗?谢谢!

var coords = [
    { 'id':'HI', 'class':'state hi', 'd': 'm 233.08751,519.30948 1.93993, ...' },
    { 'id':'AK', 'class':'state ak', 'd': 'm 158.07671,453.67502 -0.32332, ...'}
    ...
];

// Select the SVG
var svgContainer = d3.select('svg');

// Create groups with state data
var groups = svgContainer.selectAll('g')
    .data(coords)
    .enter()
    .append('g');

// Create state path for each group
groups.each(function(g){
    g.select('path')
        .data(___NEED TO RETURN THE PATH DATA HERE___)
        .enter()
        .append('path');
});

未捕获的类型错误:g.select 不是函数

【问题讨论】:

    标签: d3.js svg


    【解决方案1】:

    假设您的数据有效并且您只想处理新元素(不更新),这应该可以:

    // Select the SVG
    var svgContainer = d3.select('svg');
    
    // Create groups with state data
    var groups = svgContainer.selectAll('g')
        .data(coords)
        .enter()
        .append('g')
        .append('path')
        .attr('d', function (d) { return d.d; });
    

    我用一个例子创建了一个非常简化的fiddle

    如果你还想使用.each功能,可以如下操作:

    groups.each(function (d, i){
        // `this` (in this context) is bound to the current DOM element in the enter selection
        d3.select(this).append('path').attr('d', d.d);
    });
    

    更多详情,您可以查看API documentation

    希望对你有帮助。

    【讨论】:

    • 谢谢!你能向我解释为什么我收到“g.select is not a function”错误吗?我一直在阅读有关选择的内容,但我仍然不明白为什么它不起作用。
    • 很高兴能帮上忙 :) each 函数接受两个参数;第一个是与元素关联的数据,第二个是当前选择中的索引;这就是为什么你会得到这样的错误。我建议您阅读有关此主题的内容:bost.ocks.org/mike/join.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    相关资源
    最近更新 更多