celli
celli

Reputation: 133

Scale SVG clipPath and keep aspect ratio of Image

I have an image inside of an SVG element with a clipPath.

I want the clip path to behave like it is in my codePen https://codepen.io/celli/pen/rNBvmyx with preserveAspectRatio="none" so that I always get the same height for my clipPath which matches the parent and stretch from edge to edge of my browser.

The issue is that I want my image to preserve it's aspect-ratio and not appear squashed, while maintaining that the mask is the only element that is being squeezed and not preserving it's aspect ratio.

I tried adding css to the image to preserve the aspect ratio, but it seems to follow the SVGs preserveAspectRatio="none", but I only want that to apply to my clipPath part of the SVG.

<div id="containerId">  
<svg class="svg-graphic" preserveAspectRatio="none" viewBox="0 0 1920 1080" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" version="1.1" width="100%" height="auto">
<g>
   <clipPath id="svgmask">
      <polygon points="0,0 0,650 1920,1045 1920,394 "/>
   </clipPath>
</g> 
 <image clip-path="url(#svgmask)" style="width:100%; height:auto; max-width:100%;" xlink:href="https://img-fotki.yandex.ru/get/5607/5091629.6b/0_612e6_b9039c0d_M.jpg" />
</a>
</svg>
</div>

Upvotes: 0

Views: 2652

Answers (2)

celli
celli

Reputation: 133

I found an alternative way to do it that works in IE, without SVG, in-case anyone is interested: https://codepen.io/celli/pen/KKPReKE I wanted to use SVG, but this way seems to be the best solution by using a pseudo element and a rotated div.

<div id="head">
<div id="headAddBkgColor"></div>
    </div>
<div id="slantElm"></div>

Upvotes: 0

enxaneta
enxaneta

Reputation: 33054

A solution to your problem would be clipping a div with the image as a background. In this case you use a path instead of a polygon where the coords values are from 0 to 1 and clipPathUnits="objectBoundingBox". This won't work on IE and on Edge: https://caniuse.com/#feat=css-clip-path

*{margin:0;
  padding:0;}
#containerId {
  width: 100%;
  height: 800px;
  background-color: green;
}
@media (max-width: 800px) {
  #containerId {
    width: 100%;
    height: 500px;
    background: orange;
  }
}
.img {
  width: 100%;
  height: 100%;
  background-image: url("https://img-fotki.yandex.ru/get/5607/5091629.6b/0_612e6_b9039c0d_M.jpg");
  background-size: cover;
  -webkit-clip-path: url(#svgmask);
  clip-path: url(#svgmask);
}
<svg height="0" width="0" style="position:absolute;">
        <defs>
          <clipPath id="svgmask" clipPathUnits="objectBoundingBox">
          <path d="M0,0 L0,0.6 1,1 1,0.4"/>
          </clipPath>
        </defs>
</svg>

<div id="containerId">
  <div class="img"></div>
</div>

Upvotes: 1

Related Questions