SVG - 圖案



SVG 使用 <pattern> 元素來定義圖案。圖案使用 <pattern> 元素定義,並以平鋪方式填充圖形元素。

宣告

以下是 <pattern> 元素的語法宣告。我們只顯示了主要屬性。

<pattern
   patternUnits="units to define x,y, width and height attributes."
   patternContentUnits ="units to define co-ordinate system of contents of pattern"
   patternTransform = "definition of an additional transformation from the pattern coordinate system onto the target coordinate system"
   
   x="x-axis co-ordinate" 
   y="y-axis co-ordinate"     
   
   width="length"
   height="length"
   
   preserveAspectRatio="to preserve width/height ratio of original content"
   xlink:href="reference to another pattern" >
</pattern>

屬性

序號 名稱 & 描述
1 patternUnits - 定義圖案效果區域的單位。它指定圖案內各種長度值的座標系以及定義圖案子區域的屬性。如果 patternUnits="userSpaceOnUse",則值表示在使用“pattern”元素時當前使用者座標系中的值。如果 patternUnits="objectBoundingBox",則值表示在使用“pattern”元素時引用元素邊界框的分數或百分比。預設為 userSpaceOnUse。
2 patternContentUnits - 定義圖案內容區域的單位。它指定圖案內各種長度值的座標系以及定義圖案子區域的屬性。如果 patternContentUnits="userSpaceOnUse",則值表示在使用“pattern”元素時當前使用者座標系中的值。如果 patternContentUnits="objectBoundingBox",則值表示在使用“pattern”元素時引用元素邊界框的分數或百分比。預設為 userSpaceOnUse。
3 x - 圖案邊界框的 x 軸座標。預設為 0。
4 y - 圖案邊界框的 y 軸座標。預設為 0。
5 width - 圖案邊界框的寬度。預設為 0。
6 height - 圖案邊界框的高度。預設為 0。
7 preserveAspectRatio - 保留原始內容的寬高比。
8 xlink:href - 用於引用另一個圖案。

示例

testSVG.htm
<html>
   <title>SVG Pattern</title>
   <body>
      <h1>Sample SVG Pattern</h1>
      
      <svg width="800" height="800">
         
         <defs>
            <pattern id="pattern1" patternUnits="userSpaceOnUse"
               x="0" y="0" width="100" height="100"
               viewBox="0 0 4 4" >
               <path d="M 0 0 L 3 0 L 1.5 3 z" fill="blue" stroke="green" />
            </pattern> 
         </defs>
         
         <g>
            <text x="30" y="50" >Using Pattern (Triangles): </text>
            <rect x="100" y="100" width="300" height="300" stroke="green" 
            stroke-width="3" fill="url(#pattern1)" />
         </g> 
         
      </svg>
   
   </body>
</html>
  • 一個 <pattern> 元素定義為 pattern1。

  • 在圖案中,定義了一個視區和一個用作圖案的路徑。

  • 在 rect 元素中,fill 屬性中指定了圖案的 url,以使用之前建立的圖案填充矩形。

輸出

在 Chrome 瀏覽器中開啟 textSVG.htm。您可以使用 Chrome/Firefox/Opera 直接檢視 SVG 影像,無需任何外掛。Internet Explorer 9 及更高版本也支援 SVG 影像渲染。

廣告