首页 > 解决方案 > 如何使 SVG 向左和向右拉伸,同时保持中间的纵横比?

问题描述

我有一个由三部分组成的 SVG。我想无限拉伸左右部分,但保持中间部分完整。

这是插图。

在此处输入图像描述

viewbox我认为我的答案在于 SVG 的标签preserveAspectRatio属性附近。不过,我还没有与他们合作过,并且可以朝正确的方向轻推。

这是未拉伸 SVG 的代码,我认为我需要以某种方式增加视图框以实现所需的拉伸。

<svg width="48" height="17" viewBox="0 0 48 17" fill="none" xmlns="http://www.w3.org/2000/svg">
<line y1="0.5" x2="32" y2="0.5" stroke="#FF0000"/>
<line x1="16" y1="8.5" x2="32" y2="8.5" stroke="#00FF00"/>
<line x1="16" y1="16.5" x2="48" y2="16.5" stroke="#0000FF"/>
</svg>

这是用于代码实验的 Codepen:https ://codepen.io/jaanus1/pen/aboQpeB

标签: svg

解决方案


放:width="100%" height="100%" preserveAspectRatio="none"

<svg width="100%" height="100%" viewBox="0 0 48 17" fill="none" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
<line y1="0.5" x2="32" y2="0.5" stroke="#FF0000"/>
<line x1="16" y1="8.5" x2="32" y2="8.5" stroke="#00FF00"/>
<line x1="16" y1="16.5" x2="48" y2="16.5" stroke="#0000FF"/>
</svg>

更新

我试图做出一个新的选择。
红色和绿色两条线包含在一个SVG按比例缩放的块中。绿线进入另一个具有固定大小的 SVG 块:width="48" height="17"

为了在放大时保持所有线条的宽度相同,我添加了属性vector-effect ="non-scaling-stroke"

.one {
  position:relative;
   }
  .two {
 position:absolute;
 top:35%;
 left:50%;
  }
 <div class="one">
<svg width="100%" height="5%" viewBox="0 0 48 17" fill="none" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
<line vector-effect="non-scaling-stroke" y1="0.5" x2="32" y2="0.5" stroke="#FF0000"/>

<line vector-effect="non-scaling-stroke" x1="16" y1="16.5" x2="48" y2="16.5" stroke="#0000FF"/>
</svg>
<div class="two">
<svg width="48" height="17" viewBox="0 0 48 17">
<line x1="16" y1="8.5" x2="32" y2="8.5" stroke="#00FF00"/>
</svg>
</div>
</div>


推荐阅读