Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I scale svg graphics group to desired size(not by factor)?

Tags:

svg

I have svg graphics group (I mean paths, recatangles etc.). I want to scale group to certain size, for examle to 70,70. I know that svg provides scale transformation, but scale transformation needs scale factor that I don't know because group can have many shapes and it's not easy to determine bounding size of whole group.
I played with viewBox parameter of svg elemenent and preserveAspectRatio parameter but I could not get desired result(scale group to 70,70).
Maybe is it possible to scale group with maxtrix transform or exists other way?

like image 855
Utar Efson Avatar asked Aug 06 '11 09:08

Utar Efson


1 Answers

You can use the getBBox() function to retrieve the current size of the graphics and then use the width and height to calculate the scale factor that should be applied to the graphics to fit it into the desired size.

In the example below the graphics in the group g1 is scaled to fit in a rectange with a width and height set to 70.

<?xml version="1.0" encoding="UTF-8" ?>
<svg version="1.2" viewBox="0 0 480 240" width="480" height="240" xmlns="http://www.w3.org/2000/svg" >
 <g id="g1">
    <rect x="20" y="20" width="100" height="100" fill="red" />
    <rect x="40" y="60" width="100" height="100" fill="blue" />
 </g>
 <script type="application/ecmascript"> 

    var width=70, height=70;
    var node = document.getElementById("g1");
    var bb = node.getBBox();
    var matrix = "matrix("+width / bb.width+", 0, 0, "+height / bb.height+", 0,0)";
    node.setAttribute("transform", matrix);

 </script>
</svg>
like image 180
Jonas Pegerfalk Avatar answered Oct 27 '22 01:10

Jonas Pegerfalk