Clipping and Masking: Creating a Forest of Harry Potters! πŸ’»

|

Use a mask image as the src for an <img>

Set the background to the Harry Potter image, and create a mask image to use as the src.

For the mask image, you want the interior of the tree shape to be transparent, and the rest to match the background colour of the page (or containing element).

I found it easiest to take an square PNG with a transparent background and a green foreground colour, and erase the foreground to create the shape.

See the Pen Forest of Harry Potters (inline background image) by rob (@robjoeol) on CodePen.

Browser Support

Because it’s using a png as the src of the img, it works in almost every browser.

Use clip-path on an <img>

Creating a clip-path is pretty versatile, but is a bit difficult to create a very intricate shape. Clippy is a nice interactive tool to create the shape.

I was lazy and created an evergreen tree instead of a deciduous tree, a far simpler shape! πŸ˜…

See the Pen Forest of Harry Potters (clip-path) by rob (@robjoeol) on CodePen.

Browser Support

Is clip-path on HTML elements supported in all browsers?

Not that well at the moment, this example works in Chrome and Firefox. Firefox is the only browser to support using a clip-path on an external SVG.

Conclusion

If you want broader browser support (almost 100%), you should choose using a mask image. One drawback is that if you want it to be responsive, you need to create a mask image to match the size of each background image you use.

Clip-path is supported by Chrome and Firefox, which is about 60% of the market. A clip-path only needs to be defined once and will scale to match any image size that has the same proportions, so it is easier to support a responsive design.

Additional Reading

Related Posts