Svg clip path resizing according to viewport

Viewed 167

I'm struggling with resizing clipped svg on my HTML setup. I looked for similar solutions but I could not find any yet. I'm trying to resize clipped svg according to vertical screen viewport. Here is the codepen example of my setup:

.slider-image {
  clip-path: url(#clip);
  -webkit-clip-path: url(#clip);
}
<div>
  <img class="w-full h-full slider-image object-cover absolute top-0 left-0 z-20" src="https://images.unsplash.com/photo-1558611848-73f7eb4001a1?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1051&q=80" >
  <svg width="100%" height="90vh" viewBox="0 0 1159 548" xmlns="http://www.w3.org/2000/svg">
    <defs>
      <clipPath id="clip">
        <path d="M989 547.5H0V0H1156L1159 9L1157.5 18.5L1147 89.5L1157.5 126L1120 244.5L1088 309L1041 369.5L989 445.5L962 503.5L989 547.5Z" fill="url(#paint0_linear)"/>
        <circle cx="350" cy="168" r="80"/>
      </clipPath>
    </defs>
  </svg>                
</div>

https://codepen.io/ilkrclm/pen/oNNMQor?editors=1100

1 Answers

In this case the solution is using clipPathUnits="objectBoundingBox"

The clipPathUnits attribute indicates which coordinate system to use for the contents of the <clipPath> element.

objectBoundingBox indicates that all coordinates inside the <clipPath> element are relative to the bounding box of the element the clipping path is applied to. It means that the origin of the coordinate system is the top left corner of the object bounding box and the width and height of the object bounding box are considered to have a length of 1 unit value.

Read about clipPathUnits

Since the object bounding box is considered to have a length of 1 unit you will need to scale the path: transform="scale(0.00086)". The width of the bounding box of the path is 1159. 1/1159 = 0.00086.

I've commented out the circle since in this case is not doing anything.

*{margin:0;padding:0}
.slider-image {
  width:100%;
  clip-path: url(#clip);
  -webkit-clip-path: url(#clip);
}
<div>
  <img class="w-full h-full slider-image object-cover absolute top-0 left-0 z-20" src="https://images.unsplash.com/photo-1558611848-73f7eb4001a1?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1051&q=80" >
  <svg xmlns="http://www.w3.org/2000/svg">
    <defs>
      <clipPath id="clip" clipPathUnits="objectBoundingBox">
        <path transform="scale(0.00086)" d="M989 547.5H0V0H1156L1159 9L1157.5 18.5L1147 89.5L1157.5 126L1120 244.5L1088 309L1041 369.5L989 445.5L962 503.5L989 547.5Z" fill="url(#paint0_linear)"/>
        <!--<circle transform="scale(0.00086)" cx="350" cy="168" r="80"/>-->
      </clipPath>
    </defs>
  </svg>                
</div>

Related