HTML5之SVG 2D入门9—蒙板及mask元素介绍与应用

2020-04-21 07:21:47易采站长站整理


clip-rule属性只能用于clipPath元素的内部图形元素。例如下面的设置是起作用的:

复制代码
<g>
<clipPath id=”MyClip”>
<path d=”…” clip-rule=”evenodd” />
</clipPath>
<rect clip-path=”url(#MyClip)” … />
</g>

如果元素不在clipPath中是不起作用的。例如下面的设置是不起作用的:

复制代码
<g clip-rule=”nonzero”>
<clipPath id=”MyClip”>
<path d=”…” />
</clipPath>
<rect clip-path=”url(#MyClip)” clip-rule=”evenodd” … />
</g>

最后看裁剪路径的一个小例子:

复制代码
<svg width=”100px” height=”100px”>
<g>
<clipPath id=”MyClip”>
<path d=”M 10,10 L 10,20 L 20,20 L 20,10 Z” clip-rule=”evenodd” />
</clipPath>
</g>
<rect clip-path=”url(#MyClip)” x=”10″ y=”10″ width=”80″ height=”80″ fill=”Red” />
</svg>

矩形只有左上角10*10的区域是可见的。

蒙板- mask元素
在SVG中,你可以为渲染的对象指定任何的图形元素或者g元素作为蒙板,来将渲染对象组合到背景中。
蒙板用mask元素定义,使用蒙板的时候只需要在对象的mask属性中引用蒙板就可以了。
 mask元素可以包含任何的图形元素和容器元素(例如g)。
蒙板的效果其实大家也比较清楚,基本就是根据蒙板中每个点的颜色和透明度计算出一个最终的透明度,然后在渲染对象的时候,在对象上面罩上这个带有不同透明度的蒙板层,体现出蒙板的遮挡效果。对于渲染对象来说,只有在蒙版内的部分会按照蒙板上点的透明度来渲染,不在蒙板内的部分不显示。看下面的例子:

复制代码
<svg width=”8cm” height=”3cm” viewBox=”0 0 800 300″ version=”1.1″
xmlns=”http://www.w3.org/2000/svg” xmlns:xlink=”http://www.w3.org/1999/xlink”>
<defs>
<linearGradient id=”Gradient” gradientUnits=”userSpaceOnUse”
x1=”0″ y1=”0″ x2=”800″ y2=”0″>
<stop offset=”0″ stop-color=”white” stop-opacity=”0″ />
<stop offset=”1″ stop-color=”white” stop-opacity=”1″ />
</linearGradient>