首页 > 解决方案 > 如何使用视图框在 D3 中使 SVG 响应?

问题描述

我注意到在各种示例中,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>

标签: javascriptd3.jsresponsive

解决方案


目前您的 svg 没有调整大小,因为您已经为200x200.

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);

推荐阅读