Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the width of a scaled SVG element with JavaScript?

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>

... 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>

... 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.

like image 511
Richard JP Le Guen Avatar asked Feb 08 '12 16:02

Richard JP Le Guen


1 Answers

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.

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))

Please look this fiddle for complete code http://jsfiddle.net/b4KXr/

like image 83
Rajkamal Subramanian Avatar answered Oct 23 '22 13:10

Rajkamal Subramanian