简体   繁体   中英

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.

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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM