【问题标题】:Resizing Fullscreen World Map D3JS调整全屏世界地图 D3JS 的大小
【发布时间】:2022-01-14 05:21:21
【问题描述】:

我正在尝试使用 D3JS 制作全屏世界地图,以便在其上放置一些标记。问题是我找不到将其居中并使其对屏幕做出响应的方法(即使在智能手机上也是如此)。我怎样才能做到这一点?谢谢!

// The svg
var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

// Map and projection
var projection = d3.geoMercator()
  .translate([width / 2.15, height / 1.26])

// Load external data and boot
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson", function(data) {

  // Draw the map
  svg.append("g")
    .selectAll("path")
    .data(data.features)
    .enter().append("path")
    .attr("fill", "#DEB887")
    .attr("d", d3.geoPath()
      .projection(projection)
    )
    .style("stroke", "#13788a")
    .style("stroke-width", 0.5)
})
html,
body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background: #005f73;
}
<svg width="960" height="900"></svg>

<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/d3-geo-projection.v2.min.js"></script>

【问题讨论】:

  • 对 svg 元素使用 viewBox 属性而不是宽度和高度

标签: css svg d3.js mapping fullscreen


【解决方案1】:

使用window.innerWidth 获取窗口大小并使用便捷函数projection.fitSize 使投影跨越整个可用字段。

如果您想让更改响应窗口大小调整,只需在窗口大小更改时使用resize 事件侦听器重新绘制地图。

// The svg
var svg = d3.select("svg"),
  width = window.innerWidth,
  height = window.innerHeight;

svg.attr('width', width).attr('height', height);

// Load external data and boot
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson", function(data) {

  var projection = d3.geoMercator()
    .fitSize([width, height], data);

  // Draw the map
  svg.append("g")
    .selectAll("path")
    .data(data.features)
    .enter().append("path")
    .attr("fill", "#DEB887")
    .attr("d", d3.geoPath()
      .projection(projection)
    )
    .style("stroke", "#13788a")
    .style("stroke-width", 0.5)
})
body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background: #005f73;
}
<svg></svg>

<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/d3-geo-projection.v2.min.js"></script>

【讨论】:

    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多