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]);
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");
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.
Please shed some light on how to use viewBox
and preserveAspectRatio
attributes with force layout graphs.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…