SVG填充圖案用于用由圖像組成的圖案填充形狀。該圖案可以由SVG圖像(形狀)或位圖圖像組成。SVG填充模式看起來(lái)就像您從Photoshop等中所習(xí)慣的那樣,被稱為“平鋪”。
這是一個(gè)簡(jiǎn)單的svg填充模式示例:
<svg width="500" height="150"> <defs> <pattern id="pattern1" x="10" y="10" width="20" height="20" patternunits="userSpaceOnUse"> <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff"></circle> </pattern> </defs> <rect x="10" y="10" width="100" height="100" style="stroke: #000000; fill: url(#pattern1);"></rect> </svg>測(cè)試看看?/?
首先,在<defs>元素內(nèi)定義<pattern>元素。 圖案包含一個(gè)circle元素。 該circle元素將用作填充圖案。
其次,在CSS屬性中<rect>
聲明一個(gè)元素fill
,該元素引用<pattern>
其style
屬性中的元素ID。
其次,聲明一個(gè)<rect>元素,該元素在CSS fill屬性中引用其樣式屬性中的<pattern>元素ID。
運(yùn)行后圖像效果:
注意<pattern>元素中定義的圓是如何用作矩形的填充的。還要注意圓圈是如何從左到右,從上到下不斷重復(fù)的。
<pattern>元素的x和y屬性定義圖案開(kāi)始在<pattern>元素中的形狀中的距離。
<pattern>元素的width和height屬性定義圖案的寬度和高度。
這是從頭開(kāi)始的示例,并且將x
和y
設(shè)置為0:
<svg width="500" height="150"> <defs> <pattern id="pattern2" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse"> <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff"></circle> </pattern> </defs> <rect x="10" y="10" width="100" height="100" style="stroke: #000000; fill: url(#pattern2);" /> </svg>測(cè)試看看?/?
運(yùn)行后圖像效果:
注意,圖案現(xiàn)在是如何從圓的中間開(kāi)始的(在矩形的頂部和左側(cè))。創(chuàng)建自己的填充圖案時(shí),您將通過(guò)使用x
和y
屬性值來(lái)實(shí)現(xiàn)所需的效果。
width
和height
屬性設(shè)定的圖案的寬度和高度。
在前面的示例中width
,height
它們都設(shè)置為20,即圓的直徑。因此,圓圈一遍又一遍地重復(fù)著,中間沒(méi)有空格。
在此示例中,圖案的width(寬度)設(shè)置為25,而不是20。請(qǐng)注意,現(xiàn)在在水平圓圈之間現(xiàn)在有5個(gè)像素間隔。
這也是一個(gè)height
設(shè)置為25 的示例:
下面是相同的實(shí)例,但是x和y設(shè)置為10 (<pattern>元素內(nèi)的圓心):
現(xiàn)在,圖案從一個(gè)完整的圓圈開(kāi)始,但是仍然有多余的垂直和水平空間。
可以嵌套填充圖案,以便填充圖案在內(nèi)部使用另一個(gè)填充圖案。這是一個(gè)示例,該示例具有一個(gè)使用圓形作為填充圖案的矩形。圓內(nèi)部使用矩形作為填充圖案。
<svg width="500" height="150"> <defs> <pattern id="innerPattern" x="3" y="3" width="9" height="9" patternUnits="userSpaceOnUse" > <rect x="0" y="0" width="6" height="6" style="stroke: none; fill: #ff0000;" /> </pattern> <pattern id="outerPattern" x="12" y="12" width="25" height="25" patternUnits="userSpaceOnUse" > <circle cx="10" cy="10" r="10" style="stroke: #0000ff; fill: url(#innerPattern)" /> </pattern> </defs> <rect x="10" y="10" width="100" height="100" style="stroke: #000000; fill: url(#outerPattern);" /> </svg>測(cè)試看看?/?
運(yùn)行后圖像效果:
正如您看到的,外部矩形現(xiàn)在由圓形填充,圓形又由矩形填充。
可以使用標(biāo)準(zhǔn)SVG轉(zhuǎn)換函數(shù)轉(zhuǎn)換填充模式。您可以使用patternTransform屬性來(lái)實(shí)現(xiàn)這一點(diǎn)。下面是一個(gè)SVG模式轉(zhuǎn)換示例:
<svg width="500" height="150"> <defs> <pattern id="transformedPattern" x="10" y="10" width="20" height="20" patternUnits="userSpaceOnUse" patternTransform="rotate(35)" > <circle cx="10" cy="10" r="10" style="stroke: none; fill: #0000ff" /> </pattern> </defs> <rect x="10" y="10" width="100" height="100" style="stroke: #000000; fill: url(#transformedPattern);" /> </svg>測(cè)試看看?/?
本示例定義了一個(gè)簡(jiǎn)單的圖案,該圖案在用作矩形的填充圖案之前旋轉(zhuǎn)了35度。運(yùn)行后圖像效果: