从 SVG 中删除“填充”?

2024-04-11

I have a SVG graphic that draws a circle. When I give it a background-color with CSS, I expected it to show up only in the corners because CSS elements are never round (yes yes, border-radius...) - so I put a round graphic with a transparent background in a rectangular box with background color.
But instead, it looks like this:
enter image description here

有什么方法可以删除左侧和右侧的“填充”吗?有什么关系吗ViewBox?


有两种可能导致此问题,具体取决于 SVG 的绘制方式。

1.) SVG 中的路径/圆可能从不与左侧对齐的位置开始。

想象一下,它就像一个从点 0,0 开始的网格,宽度为 64,高度为 32,并且您已告诉圆以 32,16 为中心,半径为 16。这将留下 16 个填充点左右两侧每 32 个圆点。

<p>No padding with coordinate</p>
<svg  style="border: 1px solid red;"
      height="50px"
      viewBox="0 0 32 32" 
      xmlns="http://www.w3.org/2000/svg">
  <circle cx="16" cy="16" r="16"/>
</svg>
<p>Example above but starting at a coordinate that causes whitespace</p>
<svg  style="border: 1px solid red;"
      viewBox="0 0 64 32" 
      height="50px"
      xmlns="http://www.w3.org/2000/svg">
  <circle cx="32" cy="16" r="16"/>
</svg>

删除此问题的方法是重新定位路径,或尝试更改视图框,使其从不同的坐标开始。更改 ViewBox 的坐标并不是一个理想的解决方案,因为从非清零坐标开始变得不合逻辑,并且在向 viewbox 添加更多形状时必须记住考虑到这一点。

<p>Changing the viewbox to start at a different coordinate</p>
<svg  style="border: 1px solid red;"
      height="50px"
      viewBox="50 50 100 100" 
      xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="50"/>
</svg>
<p>Changing the 'path' so that it doesn't leave padding</p>
<svg  style="border: 1px solid red;"
      height="50px"
      viewBox="0 0 100 100" 
      xmlns="http://www.w3.org/2000/svg">
    <circle cx="50" cy="50" r="50"/>
</svg>

2.) 您的 SVG 已被告知要统一缩放。

第二个选项意味着当 SVG 放大时,SVG 中绘制的所有路径将在其尺寸上保持相同的比率。

想象一下,您有一个圆圈,并且您的 SVG 已设计为可以整齐地适合儿童,无需填充。现在我们已经将这个 SVG 框在 X 轴上缩放了 2*,在 Y 轴上缩放了 1.5*,圆将尝试在 X 方向上增长 2*,但因为它必须保持其比率并且无法增长Y 轴上的 2*,它只会在每个方向上增长 1.5*。对于 X 方向上剩余的 0.5*,它只会添加空白。

<p>Unscaled</p>
<svg  style="border: 1px solid red"
      height="100px"
      width="100px"
      viewBox="0 0 32 32" 
      xmlns="http://www.w3.org/2000/svg">
  <circle cx="16" cy="16" r="16"/>
</svg>
<p>Above circle scaled at an uneven ratio</p>
<svg  style="border: 1px solid red"
      height="50px"
      width="100px"
      viewBox="0 0 32 32" 
      xmlns="http://www.w3.org/2000/svg">
  <circle cx="16" cy="16" r="16"/>
</svg>

正如 @heycam 上面所说,要更改此设置,您可以设置 SVG 元素以允许关闭此比例缩放。这是使用属性“preserveAspectRatio”并将其设置为“none”来完成的。

<svg  style="border: 1px solid red"
      height="50px"
      width="100px"
      viewBox="0 0 32 32" 
      preserveAspectRatio="none"
      xmlns="http://www.w3.org/2000/svg">
    <circle cx="16" cy="16" r="16"/>
</svg>

希望这有助于您理解 SVG,因为它们是一个非常有用的工具!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 SVG 中删除“填充”? 的相关文章

随机推荐