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 always zero?
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 always zero?
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
.get
just returns the DOM element, jquery does not know about bbox. –
Retardant $().get()
could be used instead of the longer document.getElementById()
, as the original question uses jQuery. Robert correctly incorporated my suggestion. –
Franglais 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.
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;
};
© 2022 - 2024 — McMap. All rights reserved.