文章出處
文章列表
前面的話
本文將詳細介紹SVG裁切和蒙版
裁剪
SVG中的<clipPath>
的元素,專門用來定義剪裁路徑。必須設置的屬性是id屬性,被引用時使用
下面是一個圓形
<svg height="70" version="1.1" xmlns="http://www.w3.org/2000/svg" > <circle cx="25" cy="25" r="25" fill="#34538b" /> </svg>
通過引用clipPath進行路徑裁剪后,如下所示
<svg height="70" version="1.1" xmlns="http://www.w3.org/2000/svg" > <defs> <clipPath id="clipPath1"> <rect x="0" y="0" width="20" height="20" /> </clipPath> </defs> <circle cx="25" cy="25" r="25" fill="#34538b" clip-path="url(#clipPath1)"/> </svg>
當然了, <clipPath>
元素里面除了rect
元素, 還可以是circle
, ellipse
, line
, polyline
, polygon
, ...
等等,甚至是text
文本
<svg height="70" version="1.1" xmlns="http://www.w3.org/2000/svg" > <defs> <clipPath id="clipPath1"> <text y="20" style="font-size: 12px;">小火柴的藍色理想</text> </clipPath> </defs> <rect x="0" y="0" width="100" height="30" fill="#cd0" clip-path="url(#clipPath1)"/> </svg>
遮罩
與裁剪<clipPath>元素相比,遮罩<mask>元素所包含的子元素無須只具有線條性質的元素,可以包含任何可視化元素,甚至是<g>元素。這些可視化的子元素都必須帶上透明度的定義,因為<mask>元素是通過透明度來控制圖像與背景的遮罩效果的
蒙版中黑色代表不可見(opacity: 0),白色代表可見(opacity: 100%)
下面來使用黑白蒙版來制作一輪彎月
首先制作黑白蒙版
<svg height="70" style="background:gray" version="1.1" xmlns="http://www.w3.org/2000/svg" > <circle cx="25" cy="25" r="25" fill="white"/> <circle cx="40" cy="15" r="25" fill="black"/> </svg>
接下來,將上面的兩個circle元素制作為蒙版,并應用在一個圓形上,制作出一輪彎月
<svg height="70" style="background:gray" version="1.1" xmlns="http://www.w3.org/2000/svg" > <mask id="moon-mask"> <circle cx="25" cy="25" r="25" fill="white"/> <circle cx="40" cy="15" r="25" fill="black"/> </mask> <circle cx="25" cy="25" r="25" fill="yellow" mask="url(#moon-mask)"/> </svg>
那么黑白之間的灰色代表什么呢?從0%到100%是一個線性的變化,所以黑白中間的灰色會是半透明,而且不同灰度代表不同程度的半透明,越趨近白色可見度越高。在蒙版中的黑白漸變,應用到彩色圖層上就會產生透明度的漸變
<svg height="70" version="1.1" xmlns="http://www.w3.org/2000/svg" > <defs> <linearGradient id="Gradient1"> <stop offset="0" stop-color="white"/> <stop offset="100%" stop-color="black"/> </linearGradient> <mask id="mask1"> <rect x="0" y="0" width="100" height="50" fill="url(#Gradient1)" /> </mask> </defs> <rect x="0" y="0" width="100" height="50" fill="red" mask="url(#mask1)"/> </svg>
如果在當前矩形下,再疊加一個其他顏色的矩形,則會出現兩種顏色漸變的效果
<svg height="70" version="1.1" xmlns="http://www.w3.org/2000/svg" > <defs> <linearGradient id="Gradient1"> <stop offset="0" stop-color="white"/> <stop offset="100%" stop-color="black"/> </linearGradient> <mask id="mask1"> <rect x="0" y="0" width="100" height="50" fill="url(#Gradient1)" /> </mask> </defs> <rect x="0" y="0" width="100" height="50" fill="green"/> <rect x="0" y="0" width="100" height="50" fill="red" mask="url(#mask1)"/> </svg>
[注意]如果綠色的矩形放在紅色矩形后面,則不會出現以下這種效果
文章列表
全站熱搜