当大小为非本机时,我希望有一个内嵌svg元素的内容比例。当然,我可以将其作为单独的文件并像这样进行缩放。
index.html: <img src="foo.svg" style="width: 100%;" />
foo.svg: <svg width="123" height="456"></svg>
但是,我想通过CSS向SVG添加其他样式,因此链接外部样式不是一种选择。如何制作嵌入式SVG秤?
当大小为非本机时,我希望有一个内嵌svg元素的内容比例。当然,我可以将其作为单独的文件并像这样进行缩放。
index.html: <img src="foo.svg" style="width: 100%;" />
foo.svg: <svg width="123" height="456"></svg>
但是,我想通过CSS向SVG添加其他样式,因此链接外部样式不是一种选择。如何制作嵌入式SVG秤?
另一个简单的方法是
transform: scale(1.5);
更改SVG文件对我来说不是一个公平的解决方案,因此,我使用了相对CSS单元。
vh
,vw
,%
是非常方便的。我使用了CSS这样的样式height: 2.4vh;
来为SVG图像设置动态尺寸。
调整currentScale属性可在IE中使用(我已使用IE 11进行了测试),但不适用于Chrome。
您将需要进行如下转换:
使用JavaScript:
document.getElementById(yourtarget).setAttribute("transform", "scale(2.0)");
使用CSS:
#yourtarget {
transform:scale(2.0);
-webkit-transform:scale(2.0);
}
将SVG页面包装在Group标签中,然后将其定位为操纵整个页面:
<svg>
<g id="yourtarget">
your svg page
</g>
</svg>
注意:比例1.0为100%
混乱并发现此CSS似乎在Chrome浏览器中包含SVG,直到容器大于图像为止:
div.inserted-svg-logo svg { max-width:100%; }
似乎也可以在FF + IE 11中工作。
To specify the coordinates within the SVG image independently of the scaled size of the image, use the
viewBox
attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use thewidth
andheight
attributes to define what the width or height are with respect to the containing page.For instance, if you have the following:
It will render as a 10px by 20px triangle:
Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:
If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:
If you want to scale it up to the width of the HTML viewport:
Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):
If you actually want it to stretch horizontally, disable aspect ratio preservation with
preserveAspectRatio=none
:(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)