How does one get the height/width of an SVG group element?

前端 未结 3 2064
独厮守ぢ
独厮守ぢ 2020-12-03 05:17

I need to know the width and height of a SVG element? Im trying to use the following:

$(\'g#myGroup\').height()

...but the result is alway

相关标签:
3条回答
  • 2020-12-03 05:20

    Based on the above answer, you can create jQuery functions .widthSVG() and .heightSVG()

    /*
     * .widthSVG(className)
     * Get the current computed width for the first element in the set of matched SVG elements.
     */
    
    $.fn.widthSVG = function(){
        return ($(this).get(0)) ? $(this).get(0).getBBox().width : null;
    };
    
    /*
     * .heightSVG(className)
     * Get the current computed height for the first element in the set of matched SVG elements.
     */
    $.fn.heightSVG = function(){
        return ($(this).get(0)) ? $(this).get(0).getBBox().height : null;
    };
    
    0 讨论(0)
  • 2020-12-03 05:27

    I wasn't able to get any of the answers above to work, but did come across this solution for finding it with d3:

    var height = d3.select('#myGroup').select('svg').node().getBBox().height;
    var width = d3.select('#myGroup').select('svg').node().getBBox().width;
    

    getBBox() here will find the actual width and height of the group element. Easy as that.

    0 讨论(0)
  • 2020-12-03 05:46

    svg <g> elements don't have explicit height and width attributes, they auto size to whatever they contain. You can get their actual height/width by calling getBBox on the element though:

    var height = document.getElementById("myGroup").getBBox().height;
    

    If you're really into jquery you could write it as

    $('g#myGroup').get(0).getBBox().height;
    

    according to Reed Spool

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