我目前正在制作 D3 世界地图,其中我引入了缩放功能,根据点击可放大到任何国家或县的边界级别。
我添加了指向肯尼亚各县的气泡,该气泡在我添加的缩放功能上被放大。但我想在缩放 map 时停止气泡的缩放。
这是我当前工作的一个小工具。
https://plnkr.co/edit/nZIlJxvU74k8Nmtpduzc?p=preview
下面是缩放的代码
function clicked(d) {
var conditionalChange = d;
if(d.properties.hasOwnProperty("Country")){
var country = d.properties.Country;
var obj = data.objects.countries.geometries;
$.each(obj, function(key, value ) {
if(countries[key].properties.name == "Kenya")
{
conditionalChange = countries[key].geometry;
}
});
}
d = conditionalChange;
if (active.node() === this) return reset();
active.classed("active", false);
active = d3.select(this).classed("active", true);
var bounds = path.bounds(d),
dx = bounds[1][0] - bounds[0][0],
dy = bounds[1][1] - bounds[0][1],
x = (bounds[0][0] + bounds[1][0]) / 2,
y = (bounds[0][1] + bounds[1][1]) / 2,
scale = 1.2/ Math.max(dx / width, dy / height),
translate = [width / 2 - scale * x, height / 2 - scale * y];
g.transition()
.duration(750)
.style("stroke-width", 1/ scale + "px")
.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
}
function reset() {
active.classed("active", false);
active = d3.select(null);
g.transition()
.duration(750)
.style("stroke-width", "1px")
.attr("transform", "");
}
最佳答案
您正在缩放整个 g
元素,这会有效地缩放 map 。一切都会变大;但是,对于 map 线,您已调整笔划以反射(reflect) g
比例因子的变化:
g.transition()
.duration(750)
.style("stroke-width", 1/ scale + "px")
.attr("transform", "translate(" + translate + ")scale(" + scale + ")");
要保持圆圈大小相同,您必须根据 g
比例因子修改每个圆圈的 r
属性,对圆圈进行相同的调整:
g.selectAll(".city-circle")
.transition()
.attr("r", 5 / scale )
.duration(750);
不过,由于您实际上并未在圈子上应用类 city-circle,因此在附加它们时也需要这样做:
.attr("class","city-circle")
并且,正如您在重置时重置笔划宽度一样,您需要重置圆圈的 r
:
g.selectAll(".city-circle")
.transition()
.attr("r", 5)
.duration(750);
加在一起,我们就得到了 this .
关于javascript - 停止缩放 D3 世界地图中的气泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46916743/