SVG

SVG-Mask

SVG蒙版(mask)的基础使用教程

Posted by huangqing on April 18, 2018

SVG MASK

蒙版工作原理

设计师或者会用SketchPhotoshop一类设计工具的朋友应该都了解蒙版(mask)这个东西。接下来我先以Photoshop为例,简单解释蒙版的工作原理。

上图中创建了两个图层——蓝色的背景和红色的前景,并且在红色前景上应用了一个蒙版(右边红圈)。正常情况下红色前景应该完全遮盖住蓝色背景,但是请注意红圈中的蒙版,在这个蒙版上画了一个黑色的矩形。

蒙版中黑色代表不可见opacity: 0),白色代表可见opacity: 100%),将蒙版对应到红色图层后就很容易理解:黑色矩形在红色图层上对应的区域变成了不可见,所以下层的蓝色会显示出来。

基本用法:显示与隐藏

还是以上面Photoshop中的图为例子,我们用SVG来一步一步地创建一个这样的图形。

先创建红色前景和蓝色背景

<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>

光有了蒙版没有用,我们还需要在蒙版中添加图形元素并指定黑白颜色

<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>

进阶用法:透明度渐变

之前在讲蒙版原理的时候说到:

黑色代表不可见(opacity: 0),白色代表可见(opacity: 100%)。

那么黑白之间的灰色代表什么呢? 聪明的同学已经想到了,从0%到100%是一个线性的变化,所以黑白中间的灰色会是半透明,而且不同灰度代表不同程度的半透明,越趋近白色可见度越高。在蒙版中的黑白渐变,应用到彩色图层上就会产生透明度的渐变。

<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>