SVG图像-固定高度-保持比例-切片

时间:2018-07-02 16:06:26

标签: html css css3 svg

我有一个SVG,它需要具有固定的高度,因此当宽度为2000+像素(宽屏...)时,它不会过大 剪贴蒙版应始终可见,并且背景图像应切片而不应拉伸,我尝试了几件事,但似乎没有任何效果。

这就是我现在拥有的: https://codepen.io/bucky208/pen/OEqbPp

div {
  width: 100%;
}
<div>
     <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1024 1381.5" preserveAspectRatio="none" style="display: block; position: absolute; width: 100%;height: 400px;">
        <g id="clipgroup">
          <defs>
            <polygon id="mask" points="0,572.1 0,1381.3 1024,1040.5 1024,337.6 0,0"/>
          </defs>
          <clipPath id="mask_1_">
            <use xlink:href="#mask"  style="overflow:visible;"/>
          </clipPath>
          <g style="clip-path:url(#mask_1_);">
              <image style="overflow:visible;" width="331" height="444" id="theimage" xlink:href="https://image.ibb.co/ipbNkJ/56_E0406_E5_C8_EF897.jpg"  transform="matrix(3.1119 0 0 3.1111 -3.0528 -2.604167e-04)"></image>
          </g>
        </g>
    </svg>
  </div>

我是否需要其他包装?如何恢复图像比例?

致以最诚挚的问候,并感谢所有尝试提供帮助的人。

1 个答案:

答案 0 :(得分:1)

为了使图像填充到其容器中,但保留原始宽高比,请与objectBoundingBox大小调整和prepareAspectRatio结合使用的过滤器是您的朋友。以下代码符合我的期望:

svg {
  background: red;
}

#svgcont {
  position: absolute;
  width: 100%;
}
<div id="svgcont">
     <svg  x="0" y="0" width="100%" height="800px">

          <defs>
            <filter id="image-fill-nostretch" primitiveUnits="objectBoundingBox">
            <feImage x="0" y="0" width="1" height="1" id="theimage" xlink:href="https://image.ibb.co/ipbNkJ/56_E0406_E5_C8_EF897.jpg" preserveAspectRatio="xMidYMid slice"/>
              <feComposite operator="in" x1="SourceGraphic"/>
            </filter>
            
          <clipPath id="mask_1_" clipPathUnits="objectBoundingBox">
               <polygon id="mask" points="0,0.5 0,1 1,0.75 1,0.25 0,0"/>
          </clipPath>
          </defs>

          <g clip-path="url(#mask_1_)">
              <rect width="100%"height="100%" x="0%" y="0%" filter="url(#image-fill-nostretch)"/>
          </g>
    </svg>
</div>