Rob
Rob

Reputation: 395

How to make SVG responsive in D3 with viewbox?

I have noticed that in various examples, an SVG is responsive (changes size in response to changes in window size) and sometimes it is not responsive when using viewbox / preserveAspectRatio. Here is a very simple example. I am using viewbox and preseverAspectiRatio on the SVG element like every other example, but yet, it is not responsive, why?

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

Upvotes: 1

Views: 2895

Answers (1)

pmkro
pmkro

Reputation: 2550

Currently your svg is not resize because you have specified a fixed with for the svg container of 200x200.

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

One solution is to change these to percentages, which will rescale to the size of its parent.

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

Another possible solution is to use the Window#resize event, and change the size of the svg based on the changes.

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

I should add that in chrome you can use ResizeObserver to watch for changes to the svg parents size, and resize the svg accordingly from that.

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

Upvotes: 1

Related Questions