D3.js 旋转地图会破坏样式

问题描述

我正在尝试旋转地球仪(正投影)。 我现在所拥有的确实旋转了地球,尽管它非常波涛汹涌,并且在我拖动它后破坏了地图的外观(经纬网和海洋填充)

如何改进我的代码以使其更好? 相关代码如下:

const svg = d3.select('svg');

const projection = d3.geoOrthographic()
const graticule = d3.geoGraticule();
let pathGenerator = d3.geoPath().projection(projection);


const g = svg.append('g');

g.append('path')
    .attr('class','sphere')
    .attr('d',pathGenerator({type: 'Sphere'}));

g.append('path')
    .datum(graticule)
    .attr("class","graticule")
    .attr("d",pathGenerator);

g.call(d3.drag()
    .on("start",dragstarted)
    .on("drag",dragged)
    .on("end",dragended));


g.call(d3.zoom().on('zoom',() => {
   g.attr('transform',d3.event.transform)
 }));

function dragstarted(){
  console.log("started");
}
function dragged(){
  const rotate = projection.rotate()
    const k = 75 / projection.scale()
    //console.log(k);
    projection.rotate([
      rotate[0] + d3.event.dx * k,rotate[1] - d3.event.dy * k
    ])
    pathGenerator = d3.geoPath().projection(projection)
    svg.selectAll("path").attr("d",pathGenerator)
}
function dragended(){
  console.log("drag ended");
}

编辑: 现场演示:https://vizhub.com/Glebenator/f44ac266b14f4c92b88113fcc89c389d?edit=files&file=index.html

解决方法

好吧,我做了两件事。

  1. dragged 函数内部,我没有选择所有路径元素,而是单独选择它们...因此将行 svg.selectAll("path").attr("d",pathGenerator) 替换为 svg.selectAll(".graticule").attr("d",pathGenerator) 和 {{1 }}。

  2. 当你附加你使用 selectAll('path') 这样的国家时 svg.selectAll(".country").attr("d",pathGenerator) ...我认为这会使 d3 感到困惑,因为你已经附加了一些路径元素,所以我把它改成了一个唯一的选择器像这样g.selectAll('path').data(countries.features)

我不是 100% 确定为什么 d3 会这样(也许 @AndrewReid 可以说明问题),但我从经验中了解到,在使用 d3 附加和更新 SVG 元素时使用唯一选择器是最佳做法。>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...