我有一个使用强制布局的图形,但它具有固定宽度 w
和高度 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
属性:
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])
和这个有没有关系
请阐明如何将 viewBox
和 preserveAspectRatio
属性与强制布局图一起使用。
最佳答案
问题不在 .size()
中,而是您在 .attr("width", w) .attr("height", h) 中声明 SVG 尺寸
。去掉这两个属性就搞定了...
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");
关于javascript - 如何使 D3.js 中的力布局图响应屏幕/浏览器大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11942500/