Pursuit of Loot

Gif masking with SVGs

Posted on 19th February 2020

As a subscriber to CSS Tricks rss feed, last year I came across this article about masking gifs using svg elements and made a note that I wanted to try out this effect at some point in the future.

Being a developer, I'm always extremely conscious of the lack of skills I have in certain areas, and svg is definitely one of them. I couldn't tell you the difference between a viewbox and a viscount biscuit. Well that's not entirely accurate, but you know what I mean. There's so many attributes, and math and just thinking about it now my head is starting to hurt.

Now I'm on this 100 Days of Gatsby journey I finally came back to the article and decided to try implementing it myself. Heading over to giphy, I selected an assortment of weird and arty gifs to place over one of my favourites - Ralphy Wiggum nodding with a flute stuck up his nose.

Without too much messing around I created a styled component that let me pass in a couple of gifs to be the front and rear images. The width and height are hardcoded, as is the background colour, but these can probably be updated later to be additional props to pass in.

The code looks like this:

const Svg = styled.svg`
background-color: #000;
`;
const Gifmask = ({ foreground, background }) => {
const width = 300;
const height = Math.ceil(width * 0.73469387755102);
return (
<Svg width={width} height={height}>
<defs>
<mask id="MASK" maskUnits="userSpaceOnUse" maskContentUnits="userSpaceOnUse">
<image xlinkHref={background} height="100%" width="100%" />
</mask>
</defs>
<g mask="url(#MASK)">
<image x="0" y="0%" className="space" href={foreground} width="100%" />
</g>
</Svg>
);
};

And here's an example of what it looks like in action:

An example of a gif masking a gif

This has potential for some interesting application in future, I'm thinking of making a random gif masking generator by hooking into the giphy api and picking two random images. I'd also like to learn more about how to structure svg elements so that you adapt to the size of the items inside - the way I've made my viewbox is too strict, I want to have responsive gif masks that can scale to any size.

But these are things for another rainy day, for now head over to my experiments page and enjoy Ralph and his flute!


Enjoyed this post? Feel free to share it with your audience using the links below:

Don't see your favourite social network on the list? Feel free to let me know and I'll get it added.

Comments

©2022 Pursuit of Loot. All rights reserved.