serveAspectRatio似乎并没有改变svg图像

时间:2018-12-24 07:00:00

标签: html css svg

我已经在线阅读了许多有关viewBox属性和宽高比的教程,我很困惑。

在下面的示例中,我有第一个示例,其中viewPort和viewBox的纵横比均为5:1。然后,当视口为2:1

时,我将下一张图像的viewBox属性更改为5:1

<svg width="500" height="100" viewBox="0 0 500 10" >
  <circle r="25" cx="30" cy="30" fill="#f00" />
  <rect x="0" y="0" width="60" height="60" stroke="blue" stroke-width="2" style="fill: transparent"></rect>
</svg>

<svg width="500" height="100" viewBox="0 0 50 10" preserveAspectRatio="xMinYMin meet">
  <circle r="25" cx="30" cy="30" fill="#f00" />
  <rect x="0" y="0" width="60" height="60" stroke="blue" stroke-width="2" style="fill: transparent"></rect>
</svg>

我已将纵横比设为2:1,并添加了preserveAspectRatio="xMinYMin meet",它似乎无能为力。

preserveAspectRatio="xMinYMin meet"为什么什么也不做?

2 个答案:

答案 0 :(得分:2)

不会发生拉伸,因为在两个示例中,查看窗口的viewport-(width = "500" height = "100")都是相同的固定值

您必须删除viewport-width = "500" `` height = "100"的固定值

如果未指定viewport,则浏览器窗口的值将设置为100%。
如果未指定preserveAspectRatio,则默认为preserveAspectRatio = xMidYMid

.container
{
width:100%;
height:100%;
}
<div class="container">
<svg viewBox="0 0 500 100" >
  <circle r="25" cx="30" cy="30" fill="#f00" />
  <rect x="0" y="0" width="60" height="60" stroke="blue" stroke-width="2" style="fill: transparent"></rect>
</svg>

<h2>Yes stretching</h2>
<svg viewBox="0 0 50 100">
  <circle r="25" cx="30" cy="30" fill="#f00" />
  <rect x="0" y="0" width="60" height="60" stroke="blue" stroke-width="2" style="fill: transparent"></rect>
</svg>
</div>
  

出于适应性考虑,您还可以按百分比viewport width = "50%"

来指定height = "50%"

答案 1 :(得分:1)

您的A.R.计算是错误的。

第一个SVG的宽度设置为 500 ,高度设置为 100 ,并且viewBox属性设置为 0 0 500 10 。这意味着沿着y轴,每个坐标单元将对应于10个像素,但是沿着x轴,每个坐标单元将仅对应于1个像素。如您所见,沿x轴的纵横比为 500/500 = 1 ,沿y轴的纵横比为 100/10 = 10 。第一个SVG的宽高比为(1,10)

第二个SVG的宽度设置为 500 ,高度设置为 100 ,并且viewBox属性设置为 0 0 50 10 。如您所见,沿x轴的纵横比为 500/50 = 10 ,沿y轴的纵横比为 100/10 = 10 。这意味着沿着x轴和y轴,每个坐标单位将对应10个像素。因此,第二个SVG的宽高比为(10,10)

  

如果设置了preserveAspectRatio: xMinYMin meet,则根据两个纵横比中较小的比例缩放视图框。 Source

但是在您的第二个SVG中,该代码不起作用,因为两个轴上的宽高比相同(10,10)

要尝试代码如何工作,请将其添加到具有不同长宽比的第一个SVG中。

<h2>SVG does not have preserveAspectRatio option</h2>
<svg width="500" height="100" viewBox="0 0 500 10" >
  <circle r="25" cx="30" cy="30" fill="#f00" />
  <rect x="0" y="0" width="60" height="60" stroke="blue" stroke-width="2" style="fill: transparent"></rect>
</svg>

<h2>SVG have xMinYMin meet</h2>
<svg width="500" height="100" viewBox="0 0 500 10" preserveAspectRatio="xMinYMin meet">
  <circle r="25" cx="30" cy="30" fill="#f00" />
  <rect x="0" y="0" width="60" height="60" stroke="blue" stroke-width="2" style="fill: transparent"></rect>
</svg>