javascript - 在 svg 中将两个元素添加到同一级别

标签 javascript html svg d3.js maps

我正在使用 d3.js

嗨,我在寻找如何将相同数据的两个元素(路径和图像)附加到相同的 g(在我的 svg 内)时遇到问题。我知道如何做到这一点,但棘手的是我需要获取“路径”元素的 BBox 值,以便将“图像”元素放在中间......我的目标实际上是将小云放在 map 上的城市中心如下所示:this is the map I am trying to reproduce

在 map 上它没有居中,但我必须这样做。这是我当前的代码:

// Draw the map
svg.append("g")
    .selectAll("path")
    .data(mapEPCI.features)
    .enter()
    .append("path")
    .attr("fill", d => d.properties.color)
    .attr("d", d3.geoPath().projection(projection))
    .style("stroke", "white")
    .append("image")
        .attr("xlink:href", function(d) {
            if (d.properties.plan_air == 1)
                return ("data/page8_territoires/cloud.png")
            else if (d.properties.plan_air == 2)
                return ("data/page8_territoires/cloudgray.png")
        })
        .attr("width", "20")
        .attr("height", "15")
        .attr("x", function (d) {
            let bbox = d3.select(this.parentNode).node().getBBox();
            return bbox.x + 30})
        .attr("y", function (d) {
            return d3.select(this.parentNode).node().getBBox().y + 30})

这为我的图像获取了正确的坐标,但这是因为父节点实际上是路径...如果我将图像附加到 g 元素,有没有办法获取“BrotherNode”,或者可能是最后一个子节点“g”元素的?我不知道我是否说得足够清楚,但我希望你明白我的意思。

我对 js 有点陌生,所以也许我错过了一些我还不知道的简单内容

感谢您的帮助

最佳答案

我会在 g 级别处理您的数据,并为每个 map 要素(国家/地区)创建一个组,其中包含路径和同级图像:

<!doctype html>

<html>

<head>
  <script src="https://d3js.org/d3.v6.min.js"></script>
</head>

<body>
  <svg width="600" height="600"></svg>
  <script>
    let svg = d3.select('svg'),
      mapEPCI = {
        features: [100, 200, 300, 400]
      };

    let g = svg.selectAll('g')
      .data(mapEPCI.features)

    // enter selection is collection of g
    let ge = g.enter().append("g");

    // append a path to each g according to data
    ge.append('path')
      .attr("d", (d) => "M" + d + ",10L" + d + ",100")
      .style("stroke", "black");

    // append a sibling image
    ge.append("image")
      .attr("xlink:href", "https://placeimg.com/20/15/animals")
      .attr("width", "20")
      .attr("height", "15")
      .attr("transform", function(d) {
        // find my sibling path to get bbox
        let sibling = this.parentNode.firstChild;
        let bbox = sibling.getBBox();
        return "translate(" + (bbox.x - 20 / 2) + "," + (bbox.y + bbox.height / 2 - 15 / 2) + ")"
      });
  </script>
</body>

</html>

关于javascript - 在 svg 中将两个元素添加到同一级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65434376/

相关文章:

javascript - 如何访问从 PHP 收到的 ajax 响应中的数组元素?

javascript - 如何在 brython 中创建 websocket JSObject?

javascript - 计算变换原点以将图像缩放到视口(viewport)中间

javascript - 在不同的 &lt;script&gt; block 中访问 JavaScript 变量

javascript - 过渡动画 d3.js 的关闭路径

javascript - 如何使 svg 路径填充为进行中的动画?

javascript - 在 cordva ios 应用程序中查看另一个网页中的网页

javascript - Jquery数据表的页数

html - 无法让 li 项占用 ul 内的所有空间

javascript - path.getTotalLength 适用于文本 svg 吗?