Iterating through SVGElement paths with d3js?

I follow this guide: http://bl.ocks.org/2206529

I want to define the central region of each state, but I have two problems:

  • How to iterate over each element of an SVG state?
  • How to determine the average coordinate of this 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 does nothing.

+4
source share
1 answer

This is the misuse of attr. The attr function with the second argument is used to set the attribute, and not just to iterate through the collection. You have to use every function

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

selection.each (function)

Calls the specified function for each element in the current selection, moving to the current date d and index i, with this the context of the current DOM element. This operator is used internally by almost any other operator and can be used to call arbitrary code for each selected item. Each operator can be used to select a process recursively, using d3.select (this) within the callback function.

 states.selectAll("path").each(function(d, i) { // Get centroid(this.d) }); 
+9
source

Source: https://habr.com/ru/post/1443299/


All Articles