【问题标题】:Setting the Viewbox so that the inline SVG will “Snap” to the size of the containing element?设置 Viewbox 以便内联 SVG 将“对齐”到包含元素的大小?
【发布时间】:2019-05-02 18:19:23
【问题描述】:

我通过在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 渲染大很多。我们如何设置 viewbox 参数以使内联 SVG 始终适合包含元素的大小?

【问题讨论】:

标签: html css svg inkscape inline-svg


【解决方案1】:

为了获得正确的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}`

【讨论】:

  • 你知道是否存在更确定的方式...例如在 Inkscape 中保存时设置参数?
  • 我不使用 Inkscape。但是在 Illustrator 中,我会将 artboard 设置为适合 artwork bounds。 Inkscape 中一定有类似的东西。我想你可以在graphicdesign.stackexchange.com 中问这个
  • 您需要获取路径或路径组的边界框。我在回答中添加了一些解释。请看一看。
  • 好的 - 我也询问了图形设计,我认为这就像正确设置画板一样简单:graphicdesign.stackexchange.com/questions/124220/…
  • 也留下了答案。
【解决方案2】:

So we investigated this here to 和@Wolff 提示只要我们将画布大小设置为与绘图相同的大小,viewbox 就会自行处理。换句话说,它有正确的参数可以响应式地放入 div 中,我们就完成了。这是一个代码笔:

https://codepen.io/oleersoy/pen/xevpOw

请注意,我们使用 css 类 fs-logo-fill 设置 SVG 的颜色。

【讨论】:

    猜你喜欢
    • 2017-08-14
    • 2015-07-18
    • 2019-10-01
    • 1970-01-01
    • 2017-09-07
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多