2

I'm attempting to render the images on a site as if they were different geometric shapes. For instance, a normally square image could be displayed as a hexagon, a circle, a pentagon, an octagon, etc.

This is a responsive site, meaning that the original images will be styled with max-width: 100%;, and they'll be sized depending on their container element.

The first thought that I had was to create several transparent PNG "overlay images" with each desired geometric shape "knocked out" in the transparent area & then use z-index to overlay the masks atop the original images.

Is there a better way to do this with canvas or SVG (or even something else) and still allow for the image and mask to evenly resize as the browser window resizes? What performance considerations do I need to account for?

The final production code will be using jQuery, so if I need it for any of these approaches, it will be there.

ctrlaltdel
  • 685
  • 2
  • 10
  • 21

1 Answers1

4

You could embed the image inside SVG and use a clip path (Tinkerbin):

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
    width="100%" height="100%" viewBox="0 0 100 100">
  <clipPath id="clipCircle">
    <circle r="50" cx="50" cy="50"/>
  </clipPath>
  <clipPath id="clipTriangle">
    <polygon points="0 0 50 100 100 0"/>
  </clipPath>
  <image clip-path="url(#clipCircle)" preserveAspectRatio="none" width="100%" height="100%" xlink:href="http://upload.wikimedia.org/wikipedia/commons/e/e5/Catopsilia_pomona_3_by_kadavoor.jpg"/>
</svg>
<button onclick="document.getElementsByTagName('image')[0]
              .setAttribute('clip-path','url(#clipTriangle)')">
  change clip path
</button>

Click the button to change the circle mask to a triangular one.

Thomas W
  • 14,757
  • 6
  • 48
  • 67