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: http://msdn.microsoft.com/en-us/library/ie/bg124134(v=vs.85).aspx on simple masking and clipping.
For IE v8: You can use the chromakey filter technique found in this wonderful tutorial: thenittygritty.co/css-masking
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"> <defs> <mask id="svgmask2" maskUnits="userSpaceOnUse" maskContentUnits="userSpaceOnUse" transform="scale(1)"> <image width="100%" height="100%" xlink:href="mask.png"/> </mask> </defs> <image mask="url(#svgmask2)" width="100%" height="100%" y="0" x="0" xlink:href="sample.jpg"/> </svg> </div>
Here is the demo on JSFiddle: http://jsfiddle.net/giri_jeedigunta/Z2J34/
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 : https://developer.mozilla.org/en-US/docs/Web/API/document.createElementNS
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 http://caniuse.com/svg 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.