将svg中的两个元素附加在同一级别



我使用的是d3.js

嗨,我在寻找如何将两个元素(路径和图像(附加到来自相同数据的相同g(在我的svg中(时遇到了一个问题。我知道如何做到这一点,但棘手的是,我需要获得";路径";元件,以便放置";图像";中间的元素。。。事实上,我的目标是在城市中心的一张这样的地图上放置小云:这是我试图复制的地图

在地图上,它不是居中的,但我必须这样做。所以这是我目前的代码:

// 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级别处理您的数据,并为每个包含路径和兄弟图像的地图特征(国家(创建一个组:

<!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>

最新更新