html - 设置 Viewbox 以便内联 SVG 将 “Snap” 设置为包含元素的大小?

标签 html css svg inkscape inline-svg

我通过在 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>

然后我将其放入宽度为 200pxdiv 元素中。

这是代码笔:

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/

相关文章:

javascript - 如何删除在 Electron 中从 index.html 到 contact.html 的转换过程中创建的空白页?

html - 在 Bootstrap 中模糊表单的背景

html - 将网页放在所有屏幕尺寸的中心

javascript - SVG 上的鼠标行为滞后

javascript - jQuery 在单击操作期间选择了错误的元素

html - 在css中定位两个元素

css - 使用 css 更改 svg 图像的颜色

javascript - 用于带比例打印的 SVG

javascript - 当轴在中间对齐时如何制作网格线?

html - 在页面重定向上保持按钮状态