SVG 模式
SVG 模式 - <pattern>
<pattern>
元素用於建立圖形,該圖形會在重複的 x 和 y 座標間隔處重新繪製,以覆蓋某個區域。
所有 SVG 模式都定義在 <defs>
元素內。<defs>
元素是“定義”的縮寫,其中包含特殊元素(例如模式)的定義。
<pattern>
元素有一個必需的 id
屬性,用於標識該模式。圖形/影像然後指向要使用的模式。
然後,在 <pattern>
元素內部,我們放入一個或多個將用作填充模式的元素。
一個簡單的模式示例
以下示例建立一個用小圓填充的矩形
這是 SVG 程式碼
示例
<svg width="400" height="110" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="patt1" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
<circle cx="10" cy="10" r="10" fill="red" />
</pattern>
</defs>
<rect width="200" height="100" x="0" y="0" stroke="black" fill="url(#patt1)" />
</svg>
自己動手試一試 »
程式碼解釋
<pattern>
元素的id
屬性為模式定義了一個唯一的名稱<pattern>
元素的x
和y
屬性定義了模式在形狀內開始的距離<pattern>
元素的width
和height
屬性定義了模式的寬度和高度<pattern>
元素內的<circle>
元素定義了填充模式的形狀<rect>
元素的fill="url(#patt1)"
屬性指向“patt1”模式- 矩形將被填充模式填充
帶漸變的模式
以下示例建立一個用淺藍色小矩形和漸變圓填充的矩形
這是 SVG 程式碼
示例
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="grad1">
<stop offset="0%" stop-color="white" />
<stop offset="100%" stop-color="red" />
</linearGradient>
<pattern id="patt2" x="0" y="0" width="0.25" height="0.25">
<rect x="0" y="0" width="50" height="50" fill="lightblue" />
<circle cx="25" cy="25" r="20" fill="url(#grad1)" fill-opacity="0.8" />
</pattern>
</defs>
<rect width="200" height="200" x="0" y="0" stroke="black" fill="url(#patt2)" />
</svg>
自己動手試一試 »
程式碼解釋
<pattern>
元素的id
屬性為模式定義了一個唯一的名稱<pattern>
元素的x
和y
屬性定義了模式在形狀內開始的距離<pattern>
元素的width
和height
屬性定義了模式的寬度和高度。我們希望模式在水平方向重複 4 次,在垂直方向重複 4 次,因此我們將高度和寬度設定為 0.25(表示模式的寬度和高度是整個框大小的 25%)<pattern>
元素內的<rect>
元素定義了填充模式的一種形狀(一個淺藍色的 50x50 矩形)<pattern>
元素內的<circle>
元素定義了填充模式的另一種形狀(一個從白色到紅色的漸變圓)<circle>
元素的fill="url(#grad1)"
屬性指向“grad1”漸變<rect>
元素的fill="url(#patt2)"
屬性指向“patt2”模式- 矩形將被填充模式填充