如何使 D3.js 中的力布局图响应屏幕/浏览器大小 [英] How to make force layout graph in D3.js responsive to screen/browser size

查看:21
本文介绍了如何使 D3.js 中的力布局图响应屏幕/浏览器大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用强制布局的图形,但它有一个固定的宽度 w 和高度 h:

I have a graph using force layout, but it has a fixed width w and height h:

var svg = d3.select("#viz").append("svg")
            .attr("id", "playgraph")
            .attr("width", w)
            .attr("height", h)

var force = d3.layout.force()
              .nodes(nodes)
              .links(links)
              .charge(-1600)
              .linkDistance(45)
              .size([w, h]); 

尽管屏幕或浏览器窗口大小发生变化,但 svg 图形不会缩放或缩小.为了使其具有响应性(即自动调整自身大小),我尝试使用 viewBoxpreserveAspectRatio 属性:

which results in a svg graph that does not scale or down despite of changes in screen or browser window size. In order to make it responsive (i.e. automatically resizes itself), I tried using viewBox and preserveAspectRatio attributes:

var svg = d3.select("#viz").append("svg")
            .attr("id", "playgraph")
            .attr("width", w)
            .attr("height", h)
            .attr("viewBox", "0, 0, 600, 400")
            .attr("preserveAspectRatio", "xMidYMid meet");

不幸的是,这不起作用,因为当我调整浏览器窗口大小时没有任何反应.我想知道力图的.size([w, h])是否与此有关.

Unfortunately, this didn't work as nothing happens when I adjust the browser window size. I wonder if the .size([w, h]) of the force graph has anything to do with this.

请说明如何将 viewBoxpreserveAspectRatio 属性与强制布局图一起使用.

Please shed some light on how to use viewBox and preserveAspectRatio attributes with force layout graphs.

推荐答案

问题不在 .size() 之内,而是您在 .attr("width", w) .attr("height", h).去掉这两个属性,你就搞定了...

The problem is not within .size(), it's that you are stating the SVG dimensions in .attr("width", w) .attr("height", h). Remove these two attributes and you'll get it right...

var svg = d3.select("#viz").append("svg")
            .attr("id", "playgraph")
             //better to keep the viewBox dimensions with variables
            .attr("viewBox", "0 0 " + w + " " + h )
            .attr("preserveAspectRatio", "xMidYMid meet");

http://jsfiddle.net/aaSjd/

这篇关于如何使 D3.js 中的力布局图响应屏幕/浏览器大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆