如何使用JavaScript获取缩放后的SVG元素的宽度? [英] How do I get the width of a scaled SVG element with JavaScript?
问题描述
如果我有内联SVG,包括已缩放的元素...
If I have inline SVG, including an element which has been scaled...
<g transform="scale(sX,sY)">
<rect id="myElement" x="107" y="32" width="245" height="31" stroke="#C6C3C6" stroke-width="1px" />
</g>
...或位于具有viewBox
属性的<svg>
元素中:
... or which is in a <svg>
element with a viewBox
attribute:
<svg viewBox="20 20 5000 1230">
<g transform="scale(sX,sY)">
<rect id="myElement" x="107" y="32" width="245" height="31" stroke="#C6C3C6" stroke-width="1px" />
</g>
<svg>
...如何以编程方式找到以myElement
像素为单位的新缩放宽度-无需手动检测缩放并进行数学运算?到目前为止, myElement.getBBox().width
会返回245
而不考虑缩放.
... how can I programmatically find the new scaled width in pixels of myElement
- without manually detecting the scaling and doing the math? So far myElement.getBBox().width
returns 245
without accounting for the scaling.
推荐答案
请检查此小提琴 http://jsfiddle.net/T723E/一个>.单击矩形并记下Firebug控制台. 在这里,我已经硬编码了一个数字.3,它是div的300px宽度,包含svg节点/1000个用户单位.
please check this fiddle http://jsfiddle.net/T723E/. Click on the rectangles and note the firebug console. Here i have hard coded a number .3 which is 300px width of div containing svg node / 1000 user units.
看到赏金之后,这是我返回的用于获得缩放宽度的函数,没有太多(我不确定数学),请使用matrix.d
获取缩放高度
After seeing the bounty, this is the function i have return to get the scaled width without much (with no maths i'm not sure.)maths.Use matrix.d
for getting scaled height
var svg = document.getElementById('svg');
function getTransformedWidth(el){
var matrix = el.getTransformToElement(svg);
return matrix.a*el.width.animVal.value;
}
var ele = document.getElementById('myElement_with_scale')
console.log("scale width----", getTransformedWidth(ele))
请查看此小提琴以获得完整的代码 http://jsfiddle.net/b4KXr/
Please look this fiddle for complete code http://jsfiddle.net/b4KXr/
这篇关于如何使用JavaScript获取缩放后的SVG元素的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!