PavKR
PavKR

Reputation: 1621

Is it possible to clip a HTML element using an SVG image file as the source?

I'm trying to achieve the following effect, this is just done in photoshop with the pattern cut out of the background.

example_clip

The patterns you see in the left side are cut out of the dark background to display the image that is sitting behind them.

I have the SVG file of that image and was wondering if it is possible, if so how, to clip a solid background to those shapes using the SVG file as the source?

Upvotes: 2

Views: 2553

Answers (1)

kdau
kdau

Reputation: 2099

Yes, you can do this by giving the HTML element either a mask property that references a <mask> element in your SVG file or a clip-path property that references a <clipPath> element in your SVG file.

.element {
    /* just because of your example: */
    background-image: url(forest-road.jpg);
    /* use one of these two: */
    clip-path: url(spirograph.svg#myClipPath);
    mask: url(spirograph.svg#myMask);
}
<svg ...>
   <!-- use one of these two: -->
   <clipPath id="myClipPath">
       <!-- shapes, etc., go here -->
   </clipPath>
   <mask id="myMask">
       <!-- shapes, etc., go here -->
   </mask>
</svg>

The two CSS features work slightly differently, with masking being newer and more flexible but having some residual gaps in browser support (including needing prefixes). Either way, you'll need to adjust your SVG to be suitable. A <mask> should make a pixel white for opaque and black for transparent, with greys being intermediate opacities. On the other hand, a <clipPath> defines the region that is visible as the union of a series of shapes.

Upvotes: 3

Related Questions