user3267302
user3267302

Reputation: 311

How to resize SVG clip-path to be same size as image

I've got little problem resizing my svg clip-path to fit the image size.

I've got code like this:

<svg id="image-svg" class="clip">
     <img class="main-img" src="http://25.media.tumblr.com/tumblr_m5nre6cxkQ1qbs7p5o1_r1_500.jpg" alt="" />
</svg>
<svg class="clip">
     <clipPath id="clipPolygon">
          <polygon points="52 0,100 45,50 100,0 50">
          </polygon>
     </clipPath>
</svg>

And then i'm using css like this:

#image-svg {
  left:0;
  top:0;
}
.main-img {
  clip-path: url('#clipPolygon');
  width:90%;
}

Everything works fine, except the clip-path is much smaller then image itself. How to fix this? Here is my working fiddle:

https://jsfiddle.net/7egbccpw/

Upvotes: 3

Views: 4860

Answers (2)

Paul LeBeau
Paul LeBeau

Reputation: 101820

Firstly, your example is broken because there is no <img> element in SVGs. You want the <image> element.

#image-svg {
  left:0;
  top:0;
}
.main-img {
  clip-path: url('#clipPolygon');
  width:90%;
}
<svg id="image-svg" class="clip">
  <image class="main-img" xlink:href="http://25.media.tumblr.com/tumblr_m5nre6cxkQ1qbs7p5o1_r1_500.jpg" alt="" />
</svg>

<svg class="clip">
  <clipPath id="clipPolygon">
    <polygon points="52 0,100 45,50 100,0 50"></polygon>
  </clipPath>
</svg>

Now I presume you mean you want the clip path to automatically fit the image size. Otherwise I am guessing you would have just made the clip path coordinates bigger.

The way you do that in SVG is to use objectBoundingBox coordinates. When objectBoundingBox coordinate mode in in effect, coordinates are scaled so that (0,0) represents the top left of the target element, and (1,1) represents the bottom right of the target element. In this case, the target element is the image.

For use this mode for clip paths, you need to set clipPathUnits="objectBoundingBox". Then you just need to scale all your polygon coordinate values so that the are between 0 and 1.

#image-svg {
  width: 500px;
  height: 500px;
}
.main-img {
  clip-path: url('#clipPolygon');
  width:90%;
  height: 90%;
}
<svg id="image-svg" class="clip">
  <image class="main-img" xlink:href="http://25.media.tumblr.com/tumblr_m5nre6cxkQ1qbs7p5o1_r1_500.jpg" alt="" />
</svg>

<svg class="clip">
  <clipPath id="clipPolygon" clipPathUnits="objectBoundingBox">
    <polygon points="0.52 0 1 0.45 0.5 1 0 0.5"></polygon>
  </clipPath>
</svg>

Upvotes: 2

Temani Afif
Temani Afif

Reputation: 272955

A solution is to specify the path directly with CSS and use % for the values

.main-img {
  clip-path: polygon(50% 0%, 100% 45%, 50% 100%, 0 50%);
}
<img class="main-img" src="https://lorempixel.com/200/200/" alt="" />
<img class="main-img" src="https://lorempixel.com/100/100/" alt="" />
<img class="main-img" src="https://lorempixel.com/50/50/" alt="" />

Upvotes: 1

Related Questions