Search code examples
htmlsvgclip-path

How to define a clip path that doesn't scale with image


I'm trying to shape a polygon over some images i have in my website. My problem is that the polygon isn't always the same width and its based on the image width. I've created a codepen which you can see my problem: http://codepen.io/doronsever/pen/bdyqYq .
Here is the code that generates my svg clipath

<svg class="clip-svg" width="0" height="0">
  <defs>
    <clipPath id="clip-shape" clipPathUnits="objectBoundingBox" >
      <polygon points=".04,1, .04 .04, 0 0, 1 0, 1 1" />
    </clipPath>
  </defs>
</svg>

As you can see, the small triangle on the upper left isn't the same size on both images. How can i control it so it will always be on the same size regardless of the image width? I cannot use css clip path since i need FF support... 10x


Solution

  • Unfortunately, you can't do it that way, because as you have discovered, the clip path stretches with the image it is applied to.

    You need to use a clipPath that is defined with clipPathUnits="userSpaceOnUse". So it is of constant size and doesn't scale with the image.

    .clip-svg-inline {
        -webkit-clip-path: url("#clip-polygon");
        clip-path: url("#clip-polygon");
        position: relative;                  /* Makes clip relative to image position instead of page */
        -webkit-transform: translateZ(0px);  /* Workaround for bug in Chrome */
    }
    <img src="https://i.sstatic.net/GNWAN.jpg" class="clip-svg-inline" width="300px" >
    <img src="https://i.sstatic.net/lbwo2.jpg" class="clip-svg-inline">
    
    <svg class="clip-svg">
      <defs>
        <clipPath id="clip-polygon" clipPathUnits="userSpaceOnUse" >
          <polygon points="2000 0, 2000 2000, 12 2000, 12 12, 0 0" />
        </clipPath>
      </defs>
    </svg>