gpt4 book ai didi

javascript - 土地无故消失

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

我正在制作一个可以旋转的地球仪。我需要将国家和土地拖在一起(是的,我知道,我只能使用国家,但我需要两者)。但如果我那样做,地就会消失,我不知道出了什么问题。但是如果我评论“Countries!”,这段代码就可以完美运行。这是第一次使用这个,也许我对 topojson 有错误?

var path = d3.geoPath().projection(projection);
svg.append("path").datum(graticule).attr("class", "graticule").attr("d", path);

//Land
d3.json("https://rawgit.com/jonataswalker/map-utils/master/data/json/world-110m.json", function(error, topo) {
if (error) throw error;
var land = topojson.feature(topo, topo.objects.land);
svg.selectAll("path.foreground").data([land]).enter().append("path").attr("d", path).attr("class", "foreground");
});

//Countries!
d3.json("https://rawgit.com/Bramsiss/Globe/master/world-counries.json", function(collection) {
var countries = svg.selectAll("path").data(collection.features).enter().append("path").attr("d", path).attr("class", "country");
});

//drag
var λ = d3.scaleLinear().domain([0, width]).range([-180, 180]);
var φ = d3.scaleLinear().domain([0, height]).range([90, -90]);
var drag = d3.drag().subject(function() {
var r = projection.rotate();
return {
x: λ.invert(r[0]),
y: φ.invert(r[1])
};
}).on("drag", function() {
projection.rotate([λ(d3.event.x), φ(d3.event.y)]);
svg.selectAll(".foreground").attr("d", path);
});
svg.call(drag);

最佳答案

问题出现在这里:

svg.selectAll("path")
.data(collection.features)
.enter().append("path")
.attr("d", path)
.attr("class", "country");
});

svg.selectAll("path") 选择一条现有路径 - 世界轮廓。因此,您的输入选择不包括第一个路径 - 它已被附加。它是更新选择的一部分。您确实使用此代码为第一条路径设置了基准,但没有更新其形状。

如果你仔细看,安哥拉的边界比邻国的边界要浅,这是因为边界不是两条线(两国的边界),而是一条线。

由于您仅使用输入来创建和塑造新元素,因此地球陆地的原始轮廓没有改变。但是,当您使用更新选择来旋转地球时:

svg.selectAll(".foreground, .country").attr("d", path);   

您根据添加国家/地区时附加的数据更新所有路径的形状。由于您将绑定(bind)到 DOM(地球陆地轮廓)中第一条路径的数据替换为国家数据数组中第一项的数据,因此路径将根据新数据重新绘制。

这就是为什么如果您拖动地球,安哥拉的边界会发生变化,如果您查看 DOM,您还会注意到该国家/地区的类别为“前景”,而不是“国家/地区”。

解决方法:

使用空选择附加国家:

svg.selectAll(null)

svg.selectAll()

svg.selectAll(".country")  // since there are no elements with this class yet.

这是一个 updated pen .

关于javascript - 土地无故消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47501922/

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