【问题标题】:D3.js Rotating a map breaks stylingD3.js 旋转地图会破坏样式
【发布时间】:2021-01-18 20:58:49
【问题描述】:

我正在尝试旋转地球仪(正交投影)。 我现在所拥有的确实可以旋转地球,尽管它非常不稳定,并且在我拖动它后会破坏地图的外观(标线和海洋填充)

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

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

【问题讨论】:

  • 你有现场演示或 JSFiddle 之类的吗?了解您所说的“破坏地图外观”的含义会很有帮助。
  • 很公平,我会尝试制作一个。
  • 此外,演示网站上的地图实际上比我的本地机器看起来更平滑......我想我只需要在拖动时正确更新所有元素,但我不知道该怎么做。
  • 好吧..这是你想要的样子吗? vizhub.com/jgphilpott/…
  • @JacobPhilpott,这周会去看看,有一些建议。

标签: javascript d3.js map-projections


【解决方案1】:

好的,所以我做了两件事。

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

  2. 当您附加使用 selectAll('path') 的国家/地区时,像这样 g.selectAll('path').data(countries.features) ...我认为这会使 d3 感到困惑,因为您已经附加了一些路径元素,所以我将其更改为像这样的唯一选择器 g.selectAll('.country').data(countries.features) .

我不是 100% 确定为什么 d3 会这样(也许@AndrewReid 可以提供一些启示),但我从经验中了解到,在使用 d3 附加和更新 SVG 元素时使用唯一选择器是最佳实践。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2012-10-30
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多