Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change argument of svg <g transform=scale(X)> with JavaScript?

Tags:

javascript

svg

Hey.
Let's say that somewhere on my page I have SVG graphics. There is one group that I would like to re-scale when some event is triggered. How do I do that?
example code:

<svg onresize="getDivSize(evt)">
    <g transform=scale(13)>
        <rect id="Square" class="chart"
            width="80" height="20"
            fill="black"
            stroke-width="0px"
            rx="8" ry="8" />
         <text id="TextElement" x="13" y="15" fill="green">Text</text>
     </g>
</svg>

I want to change scale(13) argument, to do that what should be in function getScreenSize(evt) {...}?
Or how achieve similar effect in different way?

edit
As for general idea I want to resize graphic without specifying fixed values anywhere. So my divs sizes are percentage based, now I just want my graphic to exactly fit my div regardless of its size. That's why I thought of JS changing scale() argument whenever event is fired (div resize). Function would put into scale argument computation of DivSize/rectBaseSize (x or y).

like image 559
yoosiba Avatar asked Jan 18 '11 01:01

yoosiba


1 Answers

Add an id attribute to the <g> and then try this:

document.getElementById("id_of_g_element").transform.baseVal.getItem(0).setScale(new_scalex,newscale_y);

or alternatively:

document.getElementById("id_of_g_element").setAttribute("transform", "scale(" + new_scalex + "," + new_scaley + ")");

On the other hand, why don't you just use a viewBox to have the svg contents rescaled automatically? Or are there specific constraints on what should be shown? It's also possible to do some of that with non-scripted solutions based on CSS3 media-queries, see http://www.youtube.com/watch?v=YAK5el8Uvrg (don't forget to check the description for links to the demo files shown in that presentation).

like image 84
Erik Dahlström Avatar answered Sep 28 '22 00:09

Erik Dahlström