您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在d3.js中调整窗口大小时调整SVG大小

在d3.js中调整窗口大小时调整SVG大小

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

其他 2022/1/1 18:21:11 有405人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶