Get the real size of a SVG/G element

后端 未结 4 1191
耶瑟儿~
耶瑟儿~ 2020-12-24 02:31

Is there any accurate way to get the real size of a svg element that includes stroke, filters or other elements contributing to the element\'s real size from within Javascri

相关标签:
4条回答
  • 2020-12-24 02:54

    Here is an example using D3.js:

    Starting with a div:

    <div style="border:1px solid lightgray;"></div>
    

    The javascript code looks like this:

    var myDiv = d3.select('div');
    var mySvg = myDiv.append('svg');
    var myPath = mySvg.append('path');
    myPath.attr({
        'fill': '#F7931E',
        'd': 'M37,17v15H14V17H37z M50,0H0v50h50V0z'
    });
    
    // Get height and width.
    console.log(myPath.node().getBBox());
    
    0 讨论(0)
  • 2020-12-24 03:12

    You didn't specify any programming language. So I can suggest to use Inkscape.

    In the file menu you find document's properties and in the first page there's "resize page to content" command. In this way you remove all the white space around your draw and you see the real size. After width and height values apprear inside the header of svg.

    I know that Inkscape supports scripting and command line operations but I don't know if it's possible to do the trimming operatation in this way. But if it's possible you can do that from every programming language.

    0 讨论(0)
  • 2020-12-24 03:14

    You can't get the values directly. However, you can get the dimensions of the bounding rectangle:

    var el   = document.getElementById("yourElement"); // or other selector like querySelector()
    var rect = el.getBoundingClientRect(); // get the bounding rectangle
    
    console.log( rect.width );
    console.log( rect.height);
    

    It is supported at least in the actual versions of all major browser.

    Check fiddle

    0 讨论(0)
  • 2020-12-24 03:16

    Both raphael js http://dmitrybaranovskiy.github.io/raphael/ and d3 js http://d3js.org/ have various methods to find the size of an svg object or sets of svg object. It depends on if it's a circle, square, path, etc... as to which method to use.
    I suspect you are using complex shapes, so in that case bounding box would be your best bet http://raphaeljs.com/reference.html#Element.getBBox (Edit: updated reference site.) http://dmitrybaranovskiy.github.io/raphael/reference.html#Element.getBBox

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