【问题标题】:Keep SVG proportions whilst reducing window (or container) size保持 SVG 比例,同时减小窗口(或容器)大小
【发布时间】:2019-06-21 13:58:32
【问题描述】:

我有一个 SVG 图形,它是容器的子元素。

如果我希望它适合这个容器的整个宽度,我通常会使用preserveAspectRatio="none" 并将宽度设置为 100%(如果我想为 SVG 添加一些额外的高度,可以使用可选的高度值)。

但是,我希望 SVG 适合容器,但是当我将窗口拖动到更小的尺寸时,楔形(即 SVG 的对角线角度)保持在相同的角度,同时仍然填充容器。

在示例代码中,我保留了preserveAspectRatio=none 代码以显示我想要的一般效果(不同之处当然是我希望楔形的角度保持不变,因为窗口尺寸减小了) .

这可能吗?我正在努力想办法让它发挥作用。

这是一个 Codepen:https://codepen.io/emilychews/pen/pGbPby

body {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

.container {
  width: 80%;
  height: 10rem;
  background: lightblue;
  position: relative;
}

.wedge {
  width: 100%;
  left: 0;
  bottom: 0;
  height: 4rem;
  position: absolute
}
<div class="container">
  <svg class="wedge" preserveAspectRatio="none" aria-hidden="true" viewBox="0 0 376.9 122.7">
    <polyline fill="#000" points="376.9 122.69 0 122.35 376.55 0 376.9 122.69"/>
  </svg>
</div>

【问题讨论】:

  • 您可能希望为 preserveAspectRatio 设置不同的值

标签: html svg size aspect-ratio


【解决方案1】:

如果您希望 SVG 保持其纵横比而不是拉伸,则不要使用preserveAspectRatio="none"。使用不同的preserveAspectRatio 值。例如"xMinYMax slice"

body {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

.container {
  width: 80%;
  height: 10rem;
  background: lightblue;
  position: relative;
}

.wedge {
  width: 100%;
  left: 0;
  bottom: 0;
  height: 4rem;
  position: absolute
}
<div class="container">
  <svg class="wedge" preserveAspectRatio="xMinYMax slice" aria-hidden="true" viewBox="0 0 376.9 122.7">
    <polyline fill="#000" points="376.9 122.69 0 122.35 376.55 0 376.9 122.69"/>
  </svg>
</div>

但是,如果页面变得足够宽以至于楔形变得如此高以至于顶部被剪掉,那么您显然必须决定要发生什么。例如,在您的示例(以及我上面的示例)中,您将 SVG 的高度限制为4em。所以你只看到楔形的底部。

如果我将 SVG 高度更改为 100%,您会看到更多。

body {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

.container {
  width: 80%;
  height: 10rem;
  background: lightblue;
  position: relative;
}

.wedge {
  width: 100%;
  left: 0;
  bottom: 0;
  height: 100%;
  position: absolute
}
<div class="container">
  <svg class="wedge" preserveAspectRatio="xMinYMax slice" aria-hidden="true" viewBox="0 0 376.9 122.7">
    <polyline fill="#000" points="376.9 122.69 0 122.35 376.55 0 376.9 122.69"/>
  </svg>
</div>

当然,您可能还想减小楔形的角度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2016-11-26
    • 2016-08-02
    • 2018-07-17
    • 1970-01-01
    相关资源
    最近更新 更多