svg中的多个preserveAspectRatio?

时间:2017-07-09 05:06:32

标签: svg

我希望svg在我的布局中填充特定空间,因此preserveAspectRatio="none"似乎是一个很好的第一种方法。

然而,在svg中,有一个我想要拉伸/扭曲的面具。相反,它应该占据宽度的100%,高度根据其比例缩放。这两个图像说明了父级svg处于横向或纵向时的掩码行为。 (注意:图像中的灰色是<svg>的其余部分,应该伸展以适应)

面具可以有自己的aspectRatio设置吗?有没有更好的方法来实现这一目标?或者,它甚至可能吗?

example of mask when filling landscape area example of the mask when in a portrait viewport

```

<!-- this should scale according to its bounding parent -->
<svg class="fix" viewbox="0 0 2880 1620" preserveAspectRatio="none..?">

  <!-- this should scale according to some intrinsic ratio -->
  <mask id="mask" 
        maskUnits="userSpaceOnUse" 
        maskContentUnits="userSpaceOnUse">
    <rect fill="white" x="0" y="0" width="2880" height="1620" /> 
    <path fill="black" d="M57.59,60h409c344.17,.... ...."/>
  </mask>

  <rect mask="url(#mask)" x="0" y="0" width="100%" height="100%" />

</svg>

```

编辑:使用mask-image代替mask似乎是可能的(因为它有其他定位选项),但这似乎不适用于svg元素。

1 个答案:

答案 0 :(得分:1)

您不需要使用preserveAspectRatio="none"让矩形和蒙版填满页面。只需将<rect><mask>延伸到所有方向的SVG边界即可。默认情况下,根<svg>元素具有overflow: visible,因此扩展的rect将填充SVG父容器 - 只要您扩展到足够远的程度。

<rect mask="url(#mask)" x="-1000%" y="-1000%" width="3000%" height="3000%" />

我在这里使用了1000%,但如果您需要更多或更少(超过10倍),您可以调整它。

请注意,我们只使用标准默认SVG preserveAspectRatio。所以我们仍然可以获得SVG的自动中心和缩放。

&#13;
&#13;
body {
  margin: 0;
  padding: 0;
}

svg {
  width: 100vw;
  height: 100vh;
}
&#13;
<svg viewbox="0 0 2880 1620">

  <!-- this should scale according to some intrinsic ratio -->
  <mask id="mask" 
        maskUnits="userSpaceOnUse" 
        maskContentUnits="userSpaceOnUse"
        x="-1000%" y="-1000%" width="3000%" height="3000%">
    <rect fill="white" x="-1000%" y="-1000%" width="3000%" height="3000%" /> 
    <circle cx="1440" cy="810" r="400" fill="black"/>
  </mask>

  <rect mask="url(#mask)" x="-1000%" y="-1000%" width="3000%" height="3000%" />

</svg>
&#13;
&#13;
&#13;

Demo in fiddle format

相关问题