简体   繁体   English

将SVG缩放到宽度和高度

[英]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. 我遇到了一个问题,我想将多个svgs缩放到给定的宽度和高度。 Each svg elements needs to be scaled to a width and height. 每个svg元素都需要缩放到宽度和高度。 I have to use the viewbox attribute but it didn't work. 我必须使用viewbox属性,但它不起作用。 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: 此外,SVG的宽度和高度设置为100%,因此计算比例因子将是可行的方法,但简单的公式如下:

desiredWidth / svgWidth and desiredHeight / svgHeight isn't working. desiredWidth / svgWidth and desiredHeight / svgHeight不起作用。 To get the width and height of the svg, I use the getBoundingClientRect method. 为了获得svg的宽度和高度,我使用了getBoundingClientRect方法。 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. 上面的公式不起作用的原因是两个svgs在它们是相同的“符号”但具有不同宽度和高度的意义上相似,需要缩放到相同的desiredWidth和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"). 上面的公式不会将它们扩展到相同的宽度和高度,即使它们看起来相同(相同的desiredWidth,desiredHeight和“symbol”)。

Here is a sample fiddle : http://jsfiddle.net/k_ken/eZP4x/2/ 这是一个小提琴示例: 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/ jsfiddle这里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). (如果firstElementChild存在问题,您可能希望使用childNodes [1]或将id设置为要操作的组,而不是使用svg元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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