简体   繁体   中英

Iterating through SVGElement paths with d3js?

I am following this tutorial: http://bl.ocks.org/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.

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.com/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)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM