如何使用Viewbox在D3中使SVG响应?

时间:2019-05-01 18:41:19

标签: javascript d3.js responsive

我已经注意到,在各种示例中,SVG都是响应式的(响应于窗口大小的变化而改变尺寸),有时在使用viewbox / preserveAspectRatio时它不响应。 这是一个非常简单的例子。我像其他所有示例一样,在SVG元素上使用viewbox和preseverAspectiRatio,但是它没有响应,为什么?

<html>
<meta charset="utf-8">
<body>
<div id ="chart"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>

<script>
var svgContainer = d3.select("#chart")
  .append("svg")
  .attr("width", 200)
  .attr("height", 200)
  .attr("viewBox", "0 0 100 100")
  .attr("preserveAspectRatio", "xMinYMin meet")

 //Draw the Circle
var circle = svgContainer.append("circle")
  .attr("cx", 50)
  .attr("cy", 50)
  .attr("r", 50);
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

当前,您的svg不会调整大小,因为您已为200x200的svg容器指定了一个固定的。

var svgContainer = d3.select("#chart")
  .append("svg")
  .attr("width", 200) // setting fixed width
  .attr("height", 200) // setting fixed width

一种解决方案是将其更改为百分比,然后将其缩放到其父级的大小。

var svgContainer = d3.select("#chart")
  .append("svg")
  .attr("width", '100%') // percent width
  .attr("height", 100%) // percent height

另一种可能的解决方案是使用Window#resize事件,并根据更改来更改svg的大小。

window.addEventListener('resize', function () {
// select svg and resize accordingly
});

我应该补充一点,在chrome中,您可以使用ResizeObserver来监视svg父项的大小,并据此调整svg的大小。

    const resizeOb = new ResizeObserver((entries: any[]) => {
      for (const entry of entries) {
        const cr = entry.contentRect;
        const width = cr.width; // parent width
        const height = cr.height; // parent height
        // resize svg
      }
    });
    this.resizeOb.observe(svgParentElement);
相关问题