Search code examples
cssimagesvg

How to use an svg shape to mask an image?


I have an SVG shape that I would like to use as a mask so that every image that I add to it will be sort of inside that shape.

This is my shape that I would like to use as a mask:

Image to use as a mask

This is my svg code to get that mask but with black color

<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="157.000000pt" height="163.000000pt" viewBox="0 0 157.000000 163.000000" preserveAspectRatio="xMidYMid meet">
   <metadata>
      My svg Mask
   </metadata>
   <g transform="translate(0.000000,163.000000) scale(0.100000,-0.100000)"
      fill="#000000" stroke="none">
      <path d="M373 1197 c-355 -355 -363 -363 -363 -402 0 -39 8 -47 363 -402 355
         -355 363 -363 402 -363 39 0 47 8 402 363 355 355 363 363 363 402 0 39 -8 47
         -363 402 -355 355 -363 363 -402 363 -39 0 -47 -8 -402 -363z"/>
   </g>
</svg>

And this is the final result that I would like to achieve by adding an image

Final result expected

How to make any image I add to my website be masked by the svg file or the red shape in order for them to be displayed like this one ?

Final result expected


Solution

  • here's an example of applying an SVG clipping-path through CSS:

    body {
      margin: 0
    }
    
    .test {
      height: 160px;
      width: 170px;
      -webkit-clip-path: url(#shape);
      clip-path: url(#shape);
    }
    <svg width="0" height="0">
        <defs>
            <clipPath id="shape">
                <path transform="translate(0.000000,163.000000) scale(0.100000,-0.100000)" d="M373 1197 c-355 -355 -363 -363 -363 -402 0 -39 8 -47 363 -402 355
    -355 363 -363 402 -363 39 0 47 8 402 363 355 355 363 363 363 402 0 39 -8 47
    -363 402 -355 355 -363 363 -402 363 -39 0 -47 -8 -402 -363z" />
            </clipPath>
        </defs>
    </svg>
    <img class='test' src='http://placekitten.com/640/480' />

    One thing to remember is that you can't have a g (grouping tag) inside clipping mask or it won't display;

    for this reason , in your ex., you'll find the transform property directly on the path instead then on the g tag.

    fiddle