Quantcast

How to make custom shaped images via SVG clipPaths



On the web, custom cropped images have traditionally been the responsibility of an image production workflow. Whoever provides the images crops them to a shape, set them in a rectangular PNG, and... there we have custom shaped images on the web.

Today, though, we have more options to make custom cropped shapes in a more programmatic way. It requires less production time, greater flexibility, and less work from the image production side of things.

For a recent project here at Neoteric, Art Design Chicago, we needed a flexible system to apply shapes to images, handled by code rather than a production team. This is how we got here:

CSS clip-path property

CSS has a clip-path property that is part of the CSS Masking Module. It allows you to reference and apply points to create a shape that will clip an element.

img {
    clip-path: polygon(13% 15%, 49% 13%, 89% 11%, 74% 91%, 4% 91%, 8% 83%, 25% 65%, 29% 39%, 20% 36%, 9% 40%);
}

Produces:

Using SVG clipPath instead

You don’t, however, need to have the clip path in the CSS. You can reference the <clipPath> element in an SVG:

<svg class="svg-defs">
  <defs>
        <clipPath id="clipping">
          <polygon id="Star-1" points="98.4999978 153.75 38.2520165 185.424245 49.7583542 118.337123 1.01670635 70.8257603 68.3760155 61.037872 98.5000012 1.1379786e-14 128.624005 61.0378871 195.98331 70.8258091 147.241642 118.337136 158.747982 185.424247"/>
        </clipPath>
    </def>
</svg>
.clip-img.star image {
  clip-path: url(#clipping);
}

This supports Firefox and IE, too. Choose SVG clipPaths over plain CSS clip-path simple shapes if you have complex shapes or text. I used CodePen to mock up and prototype how these SVG clipPath’s would work. Here’s the basic pen that I based Art Design Chicago from:

See the Pen GjJKoj by Peter Binkowski (@peterbinks) on CodePen.

Hiccups

One of the more tricky things I ran into was that I needed to have the SVG shapes on the page that I was referencing in the clip-path URL. However, since we use the Neoteric CMS—an in-house Ruby on Rails application—we could put the SVG shapes into a partial and put the partial into any view we needed. 

I learned a lot about how SVGs work on the web. Take a look at this article on how SVG’s box positioning and coordinate system works. Having an understanding of SVGs helps understand their placement and rendering on the page.

References & More Resources: