如何使用 JavaScript 更改 svg <g transform=scale(X)> 的参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4719647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change argument of svg <g transform=scale(X)> with JavaScript?
提问by yoosiba
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 图形。当某个事件被触发时,我想重新调整一组。我怎么做?
示例代码:
<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?
我想更改 scale(13) 参数,为此应该在函数 getScreenSize(evt) {...} 中做什么?
或者如何以不同的方式达到类似的效果?
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).
编辑
至于一般想法,我想调整图形大小而不在任何地方指定固定值。所以我的 div 大小是基于百分比的,现在我只想让我的图形完全适合我的 div,而不管它的大小。这就是为什么我想到每当触发事件(div 调整大小)时 JS 更改 scale() 参数的原因。函数将放入 DivSize/rectBaseSize(x 或 y)的尺度参数计算。
回答by Erik Dahlstr?m
Add an id attribute to the <g>and then try this:
向 中添加 id 属性<g>,然后尝试以下操作:
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).
另一方面,为什么不直接使用 viewBox 来自动重新缩放 svg 内容?或者对应该显示什么有特定的限制?也可以使用基于 CSS3 媒体查询的非脚本解决方案来完成其中的一些操作,请参阅http://www.youtube.com/watch?v=YAK5el8Uvrg(不要忘记查看演示链接的说明该演示文稿中显示的文件)。
回答by Tvog
If you 'just' want an SVG to scale to the size of a DIV, you can do that with CSS
如果您“只是”想让 SVG 缩放到 DIV 的大小,则可以使用 CSS 来实现
#stretched-image {
margin: 0;
position:fixed;
top:0; left:0; right:0; bottom:0;
height:100%;
background-size:cover;
display: block;
background-position:50% 50%;
background-image: url(../img/pic.svg);
}

