简体   繁体   中英

How to make SVG container window responsive?

I am trying to make my SVG more responsive to different Windows and I did not see much in the documentation for it that works for me. How do I make my design more responsive?

This is how my HTML structured:

<body>
    <div id="toggle"></div>
    <div id="zoomArea">
        <button type="button" class="btn btn-secondary" id="reset">Reset</button>
    </div>
    <div id="container">
        <div id="tree"></div>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>

Here is my script:

let svg = d3.select("#tree")
.append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom + additionalHeight)
let g = svg.append("g")
.attr("transform", "translate(" + margin.right + "," + margin.top + ")")

SVG will be appended to the tree div and serve as the container for my graph.

I have used this as a resource, more specifically, Adam's answer: Resize svg when window is resized in d3.js but it didn't work for me. The SVG did not resize at all.

You can use the 'viewBox' attribute in your svg tag to make the svg responsive, it is the scalable in Scalable Vector Graphic. Setting the 'viewBox' attribute to the same height and width as the svg will ensure that all of the svg is visable.

 <svg viewBox='0 0 400 600' width='600' height='400'> 

There is a useful article about 'viewBox' and other svg attributes here if you want to know more. svg-viewBox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM