寻找“响应式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%; 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设置的字体大小)。如果不希望这样做,则下面有更多涉及的替代解决方案。



