在 d3.js 中调整窗口大小时调整 svg [英] Resize svg when window is resized in d3.js

查看:28
本文介绍了在 d3.js 中调整窗口大小时调整 svg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 d3.js 绘制散点图.在这个问题的帮助下:
获取屏幕大小、当前网页和浏览器窗口

I'm drawing a scatterplot with d3.js. With the help of this question :
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;

所以我可以像这样使我的情节适合用户的窗口:

So I'm able to fit my plot to the user's window like this :

var svg = d3.select("body").append("svg")
        .attr("width", x)
        .attr("height", y)
        .append("g");

现在我希望在用户调整窗口大小时可以调整绘图大小.

Now I'd like that something takes care of resizing the plot when the user resize the window.

PS:我没有在我的代码中使用 jQuery.

PS : I'm not using jQuery in my code.

推荐答案

寻找响应式 SVG",使 SVG 响应式非常简单,您不必再担心尺寸.

Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more.

我是这样做的:

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 设置的).如果这不是您想要的,下面还有更多涉及的替代解决方案.

Note: Everything in the SVG image will scale with the window width. This includes stroke width and font sizes (even those set with CSS). If this is not desired, there are more involved alternate solutions below.

更多信息/教程:

http://thenewcode.com/744/Make-SVG-Responsive

http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php

这篇关于在 d3.js 中调整窗口大小时调整 svg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆