首页 > 解决方案 > 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>

我需要另一个包装器吗?如何恢复图像比例?

亲切的问候和非常感谢大家试图提供帮助。

标签: htmlcsssvg

解决方案


为了获得图像填充以填充其容器但保留原始纵横比,结合 objectBoundingBox 大小和 preserveAspectRatio 的过滤器是您的朋友。下面的代码做我认为你想要的:

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>


推荐阅读