Posted by : Magnus Monday, 2 July 2012

screenshot

One neat thing you can do with SVG, besides creating your own image filters, is creating a clipping path (or mask) that can be used to alter the shape of your images and the boundaries of links, the latter being what most excites me because you can now easily create links that are whatever shape you’d like instead of being restricted to a box. I’ve created a quick demo demonstrating the use of a clipPath on images. These SVG images are wrapped with a link element, which you’ll notice its boundaries form around the clipPath and not the image’s original boundary box, changing the link’s boundary box to a hexagon. Go ahead and mouseover the images to see what I’m talking about.
The basic code looks like this. You first want to create a clipPath and assign an ID to it, which you’ll use on your images as a reference. Whatever you place within the clipPath will be used as the silhouette (the part that will get displayed). In my instance, I created a hexagon.
<g>
<clipPath id="hex-mask">
  <polygon points="270,0 0,160 0,485 270,645 560,485 560,160" />
</clipPath>
</g>
You might be wondering why I’m creating the clipPath and wrapping it within a grouping element rather than a defs element. This addresses a bug that I’ve noticed within Safari, and seems to be the only way to get it to work. Hopefully this gets fixed soon.
After creating our clipPath, we can then apply it to our images. Here’s an example of that:
<a xlink:href="http://example.com">
<image clip-path="url(#hex-mask)" height="100%" width="100%" xlink:href="image.jpg" />
</a>
view rawimage.svgThis Gist brought to you by GitHub.
One thing to note, in SVG we need to use the namespaced href attribute, and include the namespace definition in our SVG opening tag, like so:
<svg width="560" height="645" viewBox="0 0 560 645"
xmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<!-- Note the xmlns:xlink="http://www.w3.org/1999/xlink" line -->

Browser Support

Inline SVG and clipPaths are supported in the latest versions of Safari and IE, Chrome 17+, and Firefox 8+. You can use Modernizr to check for support and provide a fallback to a non-clipPath version.

Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Bjonk Design -