gpt4 book ai didi

javascript - 使用 d3js 遍历 SVGElement 路径?

转载 作者:搜寻专家 更新时间:2023-11-01 05:06:21 25 4
gpt4 key购买 nike

我正在学习本教程: 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com