SVG中的多个preserveAspectRatio?


Multiple preserveAspectRatio in svg?

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

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

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

example
example

```

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 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>

```

edit:使用mask-image而不是仅仅使用mask似乎是可行的(因为它具有其他定位选项),但这似乎不适用于svg元素。


您无需使用preserveAspectRatio="none"即可使矩形和遮罩填充页面。只需在所有方向上将<rect><mask>延伸超过SVG的边界即可。根<svg>元素默认为overflow: visible,因此扩展rect将填充SVG的父容器-当然,只要您扩展得足够远即可。

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

我在这里使用了1000%,但是如果您需要更多或更少(大于10倍),则可以进行调整。

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

1
2
3
4
5
6
7
8
9
body {
  margin: 0;
  padding: 0;
}

svg {
  width: 100vw;
  height: 100vh;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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>

小提琴格式的演示