如何使用ViewBox在D3中响应SVG



我已经注意到,在各种示例中,svg响应迅速(响应窗口大小的变化而变化大小(,有时在使用viewbox/preserveSpectratio时不会响应。这是一个非常简单的例子。我像其他每个示例一样在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>

当前未调整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);

最新更新