Search code examples
javascriptsvgd3.jswidthviewbox

viewBox doesn't appear to work when width & height is set


I have a viewBox on my svg element. I simply wish for it to scale the svg to scale if the browser screen has been made smaller. However, if I try to set the width & height for my svg symbol also it STOPS scaling.

    var svg = d3.select("#svgpath").append("svg:svg") 
                .attr("viewBox", "0 0 1000 730")
                .attr("width", "900")
                .attr("height", "650")
                .attr("preserveAspectRatio", "xMinYMin meet")
                .append("svg:g")
                .attr("transform", "translate(500,430)");

Could anyone tell me why is behaves normally without width & height. I wish to have a set width & height.

thanks


Solution

  • With the code you have specified, what the renderer will do is scale down the portion of your SVG document from (0,0 - 1000,730) to fit inside the rectangular viewport 900x650. Is that what you intended? It is not exactly clear from your description.

    To check, save the following equivalent SVG and open it in a browser.

    <?xml version="1.0" standalone="no"?>
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1"
         width="900" height="650" 
         viewBox="0 0 1000 730"
         preserveAspectRatio="xMinYMin meet">
      <g>
         <ellipse cx="500" cy="365" rx="500" ry="365"/>
       </g>
    </svg>
    

    The ellipse will be 900 pixels wide and 650 pixels high. It will stay that size as long as width and height are set to those values.

    However I suspect what you may have actually intended to do is scale the SVG to fit inside the "#svgpath" element (which I am guessing is a <div>(?)). If that's what you want, then what you should do instead is set width and height to "100%" instead.