Autosize an SVG?

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

提交回复
热议问题