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

查看:1142
本文介绍了如何在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图形无法缩放或缩小,尽管屏幕或浏览器窗口大小有变化。为了使其响应(即自动调整自身大小),我尝试使用 viewBox preserveAspectRatio 属性:

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.

请阐述如何使用强制布局图使用 viewBox preserveAspectRatio 属性。

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天全站免登陆