设计师或者会用Sketch、Photoshop一类设计工具的朋友应该都了解蒙版(mask)这个东西。接下来我先以Photoshop为例,简单解释蒙版的工做原理。
上图中我建立了两个图层——蓝色的背景和红色的前景,而且在红色前景上应用了一个蒙版(右边红圈)。正常状况下红色前景应该彻底遮盖住蓝色背景,可是请注意红圈中的蒙版,我在这个蒙版上画了一个黑色的矩形。svg
蒙版中黑色表明不可见(opacity: 0),白色表明可见(opacity: 100%),将蒙版对应到红色图层后就很容易理解:黑色矩形在红色图层上对应的区域变成了不可见,因此下层的蓝色会显示出来。工具
仍是以上面Photoshop中的图为例子,咱们用SVG来一步一步地建立一个这样的图形。url
先建立红色前景和蓝色背景spa
<svg width="400" height="300"> <rect id="back" x="0" y="0" width="400" height="300" fill="#d4fcff"></rect> <rect id="front" x="0" y="0" width="400" height="300" fill="#fcd3db"></rect> </svg>
在SVG中使用蒙版须要在使用前在<defs>
中定义<mask>
并为其设置一个惟一id
,而后在须要应用蒙版的元素上添加一条属性mask="url(#id)"
。设计
<svg width="400" height="300"> <defs> <mask id="opacity"></mask> </defs> <rect id="back" x="0" y="0" width="400" height="300" fill="#d4fcff"></rect> <rect id="front" x="0" y="0" width="400" height="300" fill="#fcd3db" mask="url(#opacity)"></rect> </svg>
光有了蒙版没有用,咱们还须要在蒙版中添加图形元素并指定黑白颜色。3d
<svg width="400" height="300"> <defs> <mask id="small-rect"> <rect x="0" y="0" width="400" height="300" fill="white"></rect> <rect width="100" height="100" fill="black" x="200" y="100"></rect> </mask> </defs> <rect id="back" x="0" y="0" width="400" height="300" fill="#d4fcff"></rect> <rect id="front" x="0" y="0" width="400" height="300" fill="#fcd3db" mask="url(#small-rect)"></rect> </svg>
至此一个基本的蒙版就完成了,https://codepen.io/LuXuanqing...code
以前在讲蒙版原理的时候说到:blog
黑色表明不可见(opacity: 0),白色表明可见(opacity: 100%)。图片
那么黑白之间的灰色表明什么呢? 聪明的同窗已经想到了,从0%到100%是一个线性的变化,因此黑白中间的灰色会是半透明,并且不一样灰度表明不一样程度的半透明,越趋近白色可见度越高。在蒙版中的黑白渐变,应用到彩色图层上就会产生透明度的渐变。ci
<svg width="400" height="300"> <defs> <linearGradient id='white2black'> <stop offset="0" stop-color="white"></stop> <stop offset="100%" stop-color="black"></stop> </linearGradient> <mask id="small-rect"> <rect x="0" y="0" width="400" height="300" fill="url(#white2black)"></rect> </mask> </defs> <rect id="back" x="0" y="0" width="400" height="300" fill="#d4fcff"></rect> <rect id="front" x="0" y="0" width="400" height="300" fill="#fcd3db" mask="url(#small-rect)"></rect> </svg>
https://codepen.io/LuXuanqing...
掌握上述两种用法基本上就足够应对平常需求了,可是<mask>
还有另外几个专有属性maskUnits, maskContentUnits, x, y, width, height
我如今彻底搞不懂该怎么用,但愿有所了解的朋友不吝指教。