18

I'm attempting to use ViewBox & preserveAspectRatio to automatically adjust my d3.svg.arc when the window size has changed ...

var svg = d3.select("#chart").append("svg") 
  .append("g")
  .attr("viewBox", "0 0 700 500")
  .attr("preserveAspectRatio", "xMinYMin meet")
  .attr("transform", "translate(" + r + "," + r +") rotate(180) scale(-1, -1)");

I'm a bit confused why it doesn't work at all - I've also attempted to set the preserve to "none" & delete any set margins that I had. yet still no luck - any help or advice would be appreciated.

Here's an example: http://jsfiddle.net/xwZjN/53/

Jose
  • 587
  • 2
  • 6
  • 21
  • you can get size of the window and set aspect ratio for svg. I have answered a similar question.
    [My answer](https://stackoverflow.com/a/36059527/5907434)
    – Raj sree Mar 17 '16 at 11:55

1 Answers1

30

You are applying viewBox and preserveAspectRatio to the g element, they need to be applied to the svg element:

var svg = d3.select("#chart").append("svg") 
  .attr("viewBox", "0 0 700 500")
  .attr("preserveAspectRatio", "xMinYMin meet")
     .append("g")
     .attr("transform", "translate(" + r + "," + r +") rotate(180) scale(-1, -1)");
methodofaction
  • 70,885
  • 21
  • 151
  • 164
  • Thanks for that. But interestingly when I've applied your answer my arc seems to go into the corner - I change the x & y translate, but it doesnt work. However, if I do this - http://jsfiddle.net/xwZjN/54/ that seems to work. Any reasons why? – Jose Nov 29 '12 at 19:19
  • 3
    Because your `svg` variable actually contains a `g` element, not the SVG. However, seeing D3 examples it seems that the convention is to name the root level `g` with an `svg` variable, so you have it right (answer updated). – methodofaction Nov 29 '12 at 19:29