Autosize an SVG?

后端 未结 3 2199
慢半拍i
慢半拍i 2021-02-14 03:03

Here is a code demo

I have a SVG with an unknown height. I can figure it out after I load in json and use javascript+math but is there any css I can use to dynamically s

相关标签:
3条回答
  • 2021-02-14 03:22

    An alternative is to do similar to the above JS but set viewBox (note, not viewbox!) instead of width and height from JS with values from the getBBox() call. Then use preserveAspectRatio="xMidYMid meet" or similar.

    var svg = document.getElementById("x1");
    svg.setAttribute("viewBox", "0 0 32 18.4");
    

    https://jsfiddle.net/t88pLgbb/4/

    0 讨论(0)
  • 2021-02-14 03:29

    If the SVG element does not have any width and height attributes, then the width/height should be calculated according to the CSS specs, as pointed out by Robert Longson. However, those values will not reflect the proper dimensions of the SVG's content. You can find out the proper dimensions and placement using getBBox():

    // Javascript to run after document load
    var svg = document.getElementsByTagName("svg")[0];
    var bbox = svg.getBBox();
    svg.setAttribute("width", bbox.width + "px");
    svg.setAttribute("height", bbox.height + "px");
    svg.setAttribute("viewBox", `${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`);
    <svg xmlns="http://www.w3.org/2000/svg" style="background-color: red">
      <rect x="30" y="40" width="50" height="60"/>
    </svg>

    0 讨论(0)
  • 2021-02-14 03:34

    Inspired by Thomas's answer, here's how I did it:

    if (true) {
      let svg = document.getElementById("bleh");
      let bb = svg.getBBox();
      svg.setAttribute("width", bb.width);
      svg.setAttribute("height", bb.height);
      svg.setAttribute("transform",
        "translate(-" + bb.width / 2 + ",-" + bb.height / 2 + ") \
        scale(" + 600 / bb.width + "," + 250 / bb.height + ") \
        translate(" + bb.width / 2 + "," + bb.height / 2 + ")");
    }
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    
    <div style="width: 600px; height: 250px; border: 1px solid blue;">
      <svg id="bleh">
        <path d="M0 0 T100 400 T500 500 T800 200 T0 0" fill="purple" opacity="0.8" />
        <path d="M0 0 L100 400 L500 500 L800 200 L0 0" fill="none" stroke="black" stroke-width="2" />
      </svg>
    </div>
    
    </body>
    </html>

    Goal: try to auto-fit the entire SVG graph into the div of size 600*250.

    Basically what I did was get the width and height of the SVG after it was formed, translate it 50% left and up, scale it according to the ratio of width and height difference between the 600*250 div and the SVG graph dimensions, and then translate it back 50% right and down. This way it stayed centered while I scaled it. (It doesn't seem to like actual percentages this way...)

    0 讨论(0)
提交回复
热议问题