Cross browser SVG Masking – Supports IE8, IE9, IE10, Firefox, Chrome

In one of my recent projects I  ran into performance issues with the usage of multiple  png images(each image up to 1mb). So I started to research on the masking and clipping concepts over the web but nothing was close to what I wanted to achieve.  I want the code to be simple, maintainable and mostly work on all commonly used browsers.

I’ve come up with a cross-browser solution which supports Firefox, chrome, safari, IE v9 and above. Thankfully  IE v9 and above have support for basic SVG, masking and clipping. Here are some examples from the microsoft site: on simple masking and clipping.

For IE v8: You can use the chromakey filter technique found in this wonderful tutorial:

Here is the code / some steps involved:

You don’t need to create complex vector code or .SVG files for this solution. I made made the required mask shape as mask.png and applied it on top of the sample.jpg using SVN Mask code as shown below:

    <div class="svgMask">
        <svg width="400" height="300" baseProfile="full" version="1.2">
                <mask id="svgmask2" maskUnits="userSpaceOnUse" maskContentUnits="userSpaceOnUse" transform="scale(1)">
                    <image width="100%" height="100%" xlink:href="mask.png"/>
            <image mask="url(#svgmask2)" width="100%" height="100%" y="0" x="0" xlink:href="sample.jpg"/>

Here is the demo on JSFiddle:

The important thing with SVG is the height attribute. If you don’t mention proper height nothing will be visible.

DOM Manipulation: Please refer the createlementNS on MDN :

Mobile Support: This worked perfectly fine on iPhone, iPad, Chrome on Android Phones but the native browser on the samsung s3 did not render this code.

Even though most of the online resources like said that there is support for android, it failed to render on the native browser. You can use -webkit-mask as a fallback option for scenarios like this.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s