Masking GIFs with other GIFs
The other day, Cassie Evans tweeted a really neat trick that I’ve never seen before: using SVG to mask one GIF on top of another. The effect is quite lovely, especially if you happen to grab a colorful GIF and place it on top of a monochrome one:
??
See the Pen
Masking gifs with other gifs… (svg masking is cool) by Cassie Evans (@cassie-codes)
on CodePen.
Considering I’ve never done anything with SVG masks before, I thought I could quickly look over the code and dissect it to see how Cassie made this rather lovely demo! The interesting thing about all this though is how rather simple it is.
To kick things off, we grab the GIF that we want to use as our SVG mask. We can fetch that from GIPHY:
Next we can begin writing our SVG directly in the HTML of the page: we begin by adding a tag which can be used to store assets that we’ll refer to in another part of the same SVG:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300">
<defs>
<mask id="MASK" maskunits="userSpaceOnUse"
maskcontentunits="userSpaceOnUse">
<image
xlink:href="https://media.giphy.com/media/tIwmTQ64D52XTuL8xd/giphy.gif"
height="100%"
width="100%"/>
</mask>
</defs>
</svg>
If you take a closer look at that element, you’ll see that Cassie has added an
id="MASK"
and this is how we’ll refer to the mask later on in the file, by pointing to this id
attribute.
Now we can go ahead and fetch our next animated image (but this time a cool GIF of outer space):
Let’s add that GIF into a element and apply the
mask
attribute to it, like so:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 300">
<defs>
<mask id="MASK" maskunits="userSpaceOnUse"
maskcontentunits="userSpaceOnUse">
<image
xlink:href="https://media.giphy.com/media/tIwmTQ64D52XTuL8xd/giphy.gif"
height="100%"
width="100%"/>
</mask>
</defs>
<g mask="url(#MASK)">
<image x="0" y="0%" class="space" href="https://media.giphy.com/media/MXQnyEQwBJ6eTj90L5/giphy.gif"
height="100%" width="100%"/>
</g>
</svg>
SVG code can look pretty scary at first glance, especially if you’re not familiar with it. It might be best to break all this stuff up into two parts. First, defining the mask…
<defs>
<mask id="MASK" maskunits="userSpaceOnUse"
maskcontentunits="userSpaceOnUse">
<image
xlink:href="https://media.giphy.com/media/tIwmTQ64D52XTuL8xd/giphy.gif"
height="100%"
width="100%"/>
</mask>
</defs>
…and subsequently using that mask…
<g mask="url(#MASK)">
<image x="0" y="0%" class="space" href="https://media.giphy.com/media/MXQnyEQwBJ6eTj90L5/giphy.gif"
height="100%" width="100%"/>
</g>
Once we break it up like that, it makes a lot more sense, huh? And there you have it! Two animated GIFs used as an SVG mask. It’s a super nifty trick.
Cassie made another example but this time a jumping space monster:
See the Pen
Space monster (svg masking is cool) by Cassie Evans (@cassie-codes)
on CodePen.
The post Masking GIFs with other GIFs appeared first on CSS-Tricks.