Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

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.

Upvotes: 6

Views: 4451

Answers (2)

Rajkamal Subramanian
Rajkamal Subramanian

Reputation: 6964

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/

Upvotes: 8

Chasbeen
Chasbeen

Reputation: 1436

Have you investigated the parameter you can use with getBBox()?

http://raphaeljs.com/reference.html#Element.getBBox

Upvotes: -2

Related Questions