简体   繁体   中英

Scaling SVG' to width and height

I've run into a problem where I would like to scale multiple svgs to a given width and height. Each svg elements needs to be scaled to a width and height. I have to use the viewbox attribute but it didn't work. I have used several algebraic formulas to calculate the scale factor but to no avail.

Also, the width and height of the SVG are set to 100% so calculating the scale factor would be the way to go but simple formulas like:

desiredWidth / svgWidth and desiredHeight / svgHeight isn't working. To get the width and height of the svg, I use the getBoundingClientRect method. The reason the formula above doesn't work is that two svgs that are similar in the sense that they are the same "symbol" but with different width and height needs to be scaled to the same desiredWidth and desiredHeight. The formula above doesn't scale both to the same width and height even though they are supposed to look identical (same desiredWidth, desiredHeight and "symbol").

Here is a sample fiddle : http://jsfiddle.net/k_ken/eZP4x/2/

Any help or advice on this is greatly appreciated.

You are mostly there, but a few bugs in the code and undefined elements. You can either do it that way or probably change the viewbox. Amending your code would lead me to something like the following...

     var element1 = document.getElementsByClassName("svg1")[0].firstElementChild;
     var rect1 = element1.getBoundingClientRect();
     var element2 = document.getElementsByClassName("svg2")[0].firstElementChild;
     var rect2 = element2.getBoundingClientRect();
     var desiredWidth = 90;
     var desiredHeight = 120;

     element1.setAttribute("transform", "translate(103,93) scale(" + desiredWidth / rect1.width + "," + (desiredHeight / rect1.height) + ")");

     element2.setAttribute("transform", "translate(282,93) scale(" + desiredWidth / rect2.width + "," + (desiredHeight / rect2.height) + ")");

jsfiddle here http://jsfiddle.net/eZP4x/4/

(If there is a problem with firstElementChild, you may want to use childNodes[1] or set an id to the group you want to manipulate and use that rather than the svg element).

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