gpt4 book ai didi

javascript - 叠加层未显示在数据生成的 d3 形状之上

转载 作者:行者123 更新时间:2023-11-30 17:43:38 24 4
gpt4 key购买 nike

我是 d3.js 的菜鸟。我正在使用 topoJSON 数据来渲染 map ,到目前为止效果很好。现在我想在每个国家/地区的顶部叠加一些数据,例如文本或圆圈,但我碰壁了。我有类似这样的代码:

var countries = g.append("g")
.attr("id", "countries")
.selectAll("path")
.data(topojson.feature(collection, collection.objects.countries).features)
.enter().append("path")
.attr("d", path)
.style("fill", colorize)
.attr("class", "country")
.on("click", clicked)

正确呈现我的 map 。为了在其上叠加一些圆圈,我执行以下操作:

countries
.append("circle")
.attr("r", function(d, i, j) {
return 10; // for now
})
// getCentroid below is a function that returns the
// center of the poligon/path bounding box
.attr("cy", function(d, i, j) { return getCentroid(countries[0][j])[0]})
.attr("cx", function(d, i, j) { return getCentroid(countries[0][j])[1]})
.style("fill", "red")

这非常麻烦(特别是它访问国家数组的方式),但它成功地为代表国家/地区的每条路径附加了一个圆圈。问题是圆圈存在于 SVG 标记中,但根本没有出现在文档中。我显然做错了什么,但我不知道是什么。

最佳答案

问题是您将 circle 元素附加到 path 元素,这在 SVG 中是做不到的。您需要将它们附加到父 g 元素。代码看起来像这样。

var countries = g.selectAll("g.countries")
.data(topojson.feature(collection, collection.objects.countries).features)
.enter().append("g")
.attr("id", "countries");

countries.append("path")
.datum(function(d) { return d; })
.attr("d", path)
// etc

countries.append("circles")
// etc

关于javascript - 叠加层未显示在数据生成的 d3 形状之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20564999/

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