Bucky208
Bucky208

Reputation: 86

SVG image - fixed height - keep ratio - slice

I have a SVG that needs to have a fixed height so its not super big when the width is 2000+ pixels (widescreens...) The clipping mask should always be visible and the background image should be sliced and not be stretchend, i tried several things but nothing seems to work.

This is what i have now: 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>

Do i need another wrapper around everything? How do i restore the image ratio?

Kind regards and a big thank you for everyone trying to help.

Upvotes: 0

Views: 351

Answers (1)

Michael Mullany
Michael Mullany

Reputation: 31750

In order to get image fills to fill their container but preserve the original aspect ratio, a filter combined with objectBoundingBox sizing and preserveAspectRatio is your friend. The following code does what I think you want:

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>

Upvotes: 1

Related Questions