Autosize an SVG?

后端 未结 3 2192
慢半拍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: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 + ")");
    }
    
    
    
    
    
    
    

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

提交回复
热议问题