css – d3.js Map()自动适应父容器并使用窗口调整大小

前端之家收集整理的这篇文章主要介绍了css – d3.js Map()自动适应父容器并使用窗口调整大小前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
更新:我已经在答案部分发布并接受了一个完整的解决方案。本节中的任何代码将用作与您自己的非工作代码进行比较的参考,但不能用作解决方案。

我正在建立一个仪表板,并使用d3.js添加一个世界地图,它将根据地理位置实时绘制tweets。

在d3.json()行中引用的world.json文件是可下载的HERE(被称为world-countries.json)。

该地图作为SVG容器在页面上,并使用d3渲染。

下面是相关的代码片段。

  1. <div id="mapContainer">
  2. <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="500"></svg>
  3. </div>
  1. #mapContainer svg {
  2. display:block;
  3. margin:0 auto;
  4. }
  5. #mapContainer path {
  6. fill:#DDD;
  7. stroke:#FFF;
  8. }
  1. // generate US plot
  2. function draw() {
  3. var map = d3.select("svg");
  4. var width = $("svg").parent().width();
  5. var height = $("svg").parent().height();
  6.  
  7. var projection = d3.geo.equirectangular().scale(185).translate([width/2,height/2]);
  8. var path = d3.geo.path().projection(projection);
  9. d3.json('plugins/maps/world.json',function(collection) {
  10. map.selectAll('path').data(collection.features).enter()
  11. .append('path')
  12. .attr('d',path)
  13. .attr("width",width)
  14. .attr("height",height);
  15. });
  16. }
  17. draw();
  18. latestLoop();
  1. $(window).resize(function() {
  2. draw();
  3. });

更新:我将地图缩放到可接受的大小(对于我的特定浏览器大小),但是当我更改窗口的大小时,它仍然不会缩放和居中。然而,如果我调整窗口大小,然后点击刷新,那么一旦页面被重新加载,地图就会居中。但是,由于刻度是静态的,因此它不能正确缩放。

解决方法

完整解决方案:

这是在用户释放窗口边缘以调整其大小之后调整映射大小的解决方案,并将其放在父容器中。

  1. <div id="mapContainer"></div>
  1. function draw(ht) {
  2. $("#mapContainer").html("<svg id='map' xmlns='http://www.w3.org/2000/svg' width='100%' height='" + ht + "'></svg>");
  3. map = d3.select("svg");
  4. var width = $("svg").parent().width();
  5. var height = ht;
  6.  
  7. // I discovered that the unscaled equirectangular map is 640x360. Thus,we
  8. // should scale our map accordingly. Depending on the width ratio of the new
  9. // container,the scale will be this ratio * 100. You could also use the height
  10. // instead. The aspect ratio of an equirectangular map is 2:1,so that's why
  11. // our height is half of our width.
  12.  
  13. projection = d3.geo.equirectangular().scale((width/640)*100).translate([width/2,width/2);
  14. });
  15. }
  16. draw($("#mapContainer").width()/2);
  1. $(window).resize(function() {
  2. if(this.resizeTO) clearTimeout(this.resizeTO);
  3. this.resizeTO = setTimeout(function() {
  4. $(this).trigger('resizeEnd');
  5. },500);
  6. });
  7.  
  8. $(window).bind('resizeEnd',function() {
  9. var height = $("#mapContainer").width()/2;
  10. $("#mapContainer svg").css("height",height);
  11. draw(height);
  12. });

猜你在找的CSS相关文章