SVG圖案一般用於SVG圖形對象的填充fill
或描邊stroke
。這個圖形可以是一個SVG元素,也可以是位圖圖像,通過<pattern>
元素在x
軸或y
軸方向以固定的間隔平鋪。
<pattern>是SVG的一個圖案填充標簽,可以在pattern中定義好圖案,然后通過id引用來對某個圖形進行填充,<pattern>的width/height屬性默認是根據所填充圖形的百分比來確定的。
下面我們結合實例來講解。
<svg width="1000" height="1000">
<defs>
<pattern id="grid" x="100" y="100" width="0.2" height="0.2" patternUnits="objextBoundingBox">
<circle cx="10" cy="10" r="5" fill="red"></circle>
<polygon points="30 10 60 50 0 50" fill="green"></polygon>
</pattern>
</defs>
<rect x="100" y="100" width="400" height="300" fill="url(#grid)" stroke="blue"></rect>
</svg>
效果如下:
分析代碼:
在<defs>
標簽內定義圖案,<pattern>
元素中的內容直到引用的時候才會顯示。
<pattern>設置id為"grid",x、y值的改變決定圖案的位置,寬度、高度默認為pattern圖案占填充圖形的百分比。
在<pattern>內部定義了兩個圖形,<circle>和<polugon>。
將patternUnits值默認為objextBoundingBox,指pattern大小是占rect所填充圖形的大小
在外部定義了一個<rect>矩形,在矩形的fill中引用id名。
將填充圖形rect的width改為200時:
<rect x="100" y="100" width="200" height="200" fill="url(#grid)" stroke="blue"></rect>
圖案的個數並沒有改變,<pattern>的width/height屬性默認是根據所填充圖形的百分比來確定的。
將patternUnits設置為userSpaceOnUse時,效果如下:
<svg width="1000" height="1000"> <defs> <pattern id="grid" x="100" y="100" width="80" height="60" patternUnits="userSpaceOnUse"> <!-- <path stroke="#f0f0f0" fill="none" d="M0,0H20V20"></path> --> <circle cx="10" cy="10" r="5" fill="red"></circle> <polygon points="30 10 60 50 0 50" fill="green"></polygon> </pattern> </defs> <rect x="100" y="100" width="400" height="300" fill="url(#grid)" stroke="blue"></rect> </svg>
pattern標簽另外的兩個屬性為patternUnits和patternContentUnits,兩個屬性值一樣,但patternUnits默認值為objectBoundingBox,而patternContentUnits默認值為userSpaceOnUse,patternContentUnits用來設置pattern內圖案的單位大小,如上面實例中的circle、polygon。
userSpaceOnUse:x
、y
、width
和height
表示的值都是當前用戶坐標系統的值。也就是說,這些值沒有縮放,都是絕對值。比如上面的例子中:將pattern中width、height設為80、60時
,相當於width、height為0.2。
objectBoundingBox(默認值):x
、y
、width
和height
的值都是占外框(包裹pattern的元素)的百分比。比如上面的例子中:將pattern中width、height設為1時
,相當於pattern內的圖案占rect的百分百,上面實例設置為0.2,相當於占rect的20%。