最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Iterating through SVGElement paths with d3js? - Stack Overflow

programmeradmin3浏览0评论

I am following this tutorial:

I want to determine the center area of every state, but I have two problems:

  1. How do I iterate over every state's SVG element?
  2. How do I determine the middle coordinate of that particular SVG element?

My g element contains many paths, where each path represents a state. It seems that when I use the following code:

states.selectAll("path")

I want to find the center of the path using:

    states.selectAll("path").attr("d", function(d) {
        // Get centroid(d)
    });

But the function parameter doesn't do anything.

I am following this tutorial: http://bl.ocks/2206529

I want to determine the center area of every state, but I have two problems:

  1. How do I iterate over every state's SVG element?
  2. How do I determine the middle coordinate of that particular SVG element?

My g element contains many paths, where each path represents a state. It seems that when I use the following code:

states.selectAll("path")

I want to find the center of the path using:

    states.selectAll("path").attr("d", function(d) {
        // Get centroid(d)
    });

But the function parameter doesn't do anything.

Share Improve this question edited Mar 3, 2013 at 14:26 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Oct 31, 2012 at 18:45 egidraegidra 9,08721 gold badges67 silver badges92 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

This is the incorrect use of attr. The attr function with a second argument is used for setting an attribute, not simply for iterating over a collection. You should use the each function

https://github./mbostock/d3/wiki/Selections#wiki-each

selection.each(function)

Invokes the specified function for each element in the current selection, passing in the current datum d and index i, with the this context of the current DOM element. This operator is used internally by nearly every other operator, and can be used to invoke arbitrary code for each selected element. The each operator can be used to process selections recursively, by using d3.select(this) within the callback function.

states.selectAll("path").each(function(d, i) {

        // Get centroid(this.d)
});
发布评论

评论列表(0)

  1. 暂无评论