javascript - 使用 d3js 遍历 SVGElement 路径?

标签 javascript svg d3.js

我正在学习本教程: http://bl.ocks.org/2206529

我想确定每个州的中心区域,但我有两个问题:

  1. 如何遍历每个状态的 SVG 元素?
  2. 如何确定特定 SVG 元素的中间坐标?

我的 g 元素包含许多路径,其中每个路径代表一个状态。似乎当我使用以下代码时:

states.selectAll("path")

我想使用以下方法找到路径的中心:

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

但是函数参数没有做任何事情。

最佳答案

这是对 attr 的错误使用。带有第二个参数的 attr 函数用于设置属性,而不仅仅是迭代集合。你应该使用每个函数

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

关于javascript - 使用 d3js 遍历 SVGElement 路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13165568/

相关文章:

ios - 如何获得没有锯齿的 iOS 矢量图像?

javascript - 如何在 D3 中 append 多个矩形?

javascript - jquery 无法获取字符串数组

javascript - 如何使用 JavaScript 检查文件是否存在?

javascript - 使用 javascript 分割字符串并获取 url 值的最佳方法

path - 完美水平路径的 SVG 渐变

Javascript 不识别点击事件

html - Div 在 SVG 标签内居中

javascript - 指定当用户单击时在圆弧上插入圆的起点

javascript - 删除D3中的线元素