我通过在 inkscape 中另存为“优化的 SVG”来创建这个简单的内联 SVG。在保存之前,我将尺寸设置为 200X200px。
<div style="width: 200px; background-color: red;">
<?xml version="1.0" encoding="UTF-8"?>
<svg viewBox="0 0 200 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<g>
<path class="fs-logo-fill" d="m71.679 40.782v52.917h52.917v-52.917zm26.458 7.2166a19.242 19.242 0 0 1 19.242 19.242 19.242 19.242 0 0 1-19.242 19.242 19.242 19.242 0 0 1-19.242-19.242 19.242 19.242 0 0 1 19.242-19.242z"/>
</g>
</svg>
然后我将其放入宽度为 200px
的 div
元素中。
这是代码笔:
https://codepen.io/oleersoy/pen/dLxvEJ
可以看出,红色 div 比内联 svg 渲染大很多。我们如何设置 View 框参数,以便内联 SVG 始终适合包含元素的大小?
最佳答案
为了获得正确的 viewBox,您需要获取路径边界框的大小,并使用获得的值来定义 viewBox
。
console.log(thePath.getBBox())
<div style="width: 200px; background-color: red;">
<svg viewBox="71.68 40.782 52.92 52.92" style="display:block;">
<g>
<path id="thePath" class="fs-logo-fill" d="m71.679 40.782v52.917h52.917v-52.917zm26.458 7.2166a19.242 19.242 0 0 1 19.242 19.242 19.242 19.242 0 0 1-19.242 19.242 19.242 19.242 0 0 1-19.242-19.242 19.242 19.242 0 0 1 19.242-19.242z"/>
</g>
</svg>
</div>
在这种情况下,路径的边界框是:
let BB = {
"x": 71.67900085449219,
"y": 40.78200149536133,
"width": 52.91699981689453,
"height": 52.9170036315918
}
viewBox
将具有以下方面:
viewBox=`${BB.x} ${BB.y} ${BB.width} ${BB.height}`
关于html - 设置 Viewbox 以便内联 SVG 将 “Snap” 设置为包含元素的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958117/