我正在尝试添加缩放到英国地图与D3FC标签布局。但当我放大时,标签就会移位。据我所知,每次调用缩放时,我都必须使用d3fc-label-layout重新计算位置,但不确定如何做到这一点,这里是一个小提琴https://jsfiddle.net/benderlio/cyvqase5/11/
var zoom = d3.zoom()
.scaleExtent([1, 28])
.on('zoom', function () {
svg.selectAll('path')
.attr('transform', d3.event.transform);
svg.selectAll("circle")
.attr('transform', d3.event.transform);
svg.selectAll("text")
.attr('transform', d3.event.transform);
});
svg.call(zoom);发布于 2021-03-17 01:04:02
我能够通过在标签本身而不是圆圈和文本项上应用转换来同步点和文本的缩放。
我根据投影重新计算位置,并根据缩放变换进行调整:
const t=d3.event.transform;
svg.selectAll('path')
.attr('transform', t);
svg.selectAll(".label")
.attr('transform', d => {
const p=projection(d.geometry.coordinates)
return `translate(${ p[0] * t.k + t.x }, ${ p[1] * t.k + t.y }) scale(${ t.k })`
})你可以在这里看到它的工作原理:https://jsfiddle.net/p94xhorv/8/
编辑:添加代码以在缩放时处理布局
我更改了代码,在用户缩放时重新计算布局,以防止根据OP对我原始答案的评论,城市变得“隐藏”。
.on('zoom', function () {
const t=d3.event.transform;
svg.selectAll('path')
.attr('transform', t);
labels.position(function (d) {
const p=projection(d.geometry.coordinates)
return [p[0]*t.k+t.x, p[1]*t.k+t.y]
});
svg.datum(places.features)
.call(labels);
});下面是更新后的jsfiddle https://jsfiddle.net/rpv9743n/
https://stackoverflow.com/questions/66599564
复制相似问题