我正在使用 d3.js 绘制散点图。在这个问题的帮助下:
Get the size of the screen, current web page and browser window
我正在使用这个答案:
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
所以我可以像这样将我的情节适合用户的窗口:
var svg = d3.select("body").append("svg")
.attr("width", x)
.attr("height", y)
.append("g");
现在我希望在用户调整窗口大小时能够调整绘图大小。
PS : 我的代码中没有使用 jQuery。
最佳答案
寻找“响应式 SVG” 让 SVG 响应式非常简单,您不必再担心尺寸问题。
我是这样做的:
d3.select("div#chartId")
.append("div")
// Container class to make it responsive.
.classed("svg-container", true)
.append("svg")
// Responsive SVG needs these 2 attributes and no width and height attr.
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 600 400")
// Class to make it responsive.
.classed("svg-content-responsive", true)
// Fill with a rectangle for visualization.
.append("rect")
.classed("rect", true)
.attr("width", 600)
.attr("height", 400);
.svg-container {
display: inline-block;
position: relative;
width: 100%;
padding-bottom: 100%; /* aspect ratio */
vertical-align: top;
overflow: hidden;
}
.svg-content-responsive {
display: inline-block;
position: absolute;
top: 10px;
left: 0;
}
svg .rect {
fill: gold;
stroke: steelblue;
stroke-width: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="chartId"></div>
注意: SVG 图像中的所有内容都将随窗口宽度缩放。这包括笔画宽度和字体大小(即使是用 CSS 设置的)。如果不希望这样做,下面还有更多涉及的替代解决方案。
更多信息/教程:
http://thenewcode.com/744/Make-SVG-Responsive
http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php
关于javascript - 在 d3.js 中调整窗口大小时调整 svg 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16265123/