基本形狀
大多數 SVG 繪製使用幾種基本形狀。這些形狀的用途從其名稱中可以很明顯地看出。其中一些確定其位置和大小的引數已經給出,但元素引用可能包含更準確和完整的描述,以及此處未涵蓋的其他屬性。但是,由於它們在大多數 SVG 文件中使用,因此有必要對它們進行某種介紹。
要插入形狀,您需要在文件中建立一個元素。不同的元素對應不同的形狀,並採用不同的引數來描述這些形狀的大小和位置。有些是略微冗餘的,因為它們可以透過其他形狀建立,但它們都存在是為了您的方便,並使您的 SVG 文件儘可能短和可讀。所有基本形狀都在下圖中顯示。
生成該影像的程式碼類似於以下程式碼
xml
<?xml version="1.0" standalone="no"?>
<svg width="200" height="250" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect x="10" y="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/>
<rect x="60" y="10" rx="10" ry="10" width="30" height="30" stroke="black" fill="transparent" stroke-width="5"/>
<circle cx="25" cy="75" r="20" stroke="red" fill="transparent" stroke-width="5"/>
<ellipse cx="75" cy="75" rx="20" ry="5" stroke="red" fill="transparent" stroke-width="5"/>
<line x1="10" x2="50" y1="110" y2="150" stroke="orange" stroke-width="5"/>
<polyline points="60 110 65 120 70 115 75 130 80 125 85 140 90 135 95 150 100 145"
stroke="orange" fill="transparent" stroke-width="5"/>
<polygon points="50 160 55 180 70 180 60 190 65 205 50 195 35 205 40 190 30 180 45 180"
stroke="green" fill="transparent" stroke-width="5"/>
<path d="M20,230 Q40,205 50,230 T90,230" fill="none" stroke="blue" stroke-width="5"/>
</svg>
注意:stroke、stroke-width 和 fill 屬性將在本教程後面的部分中解釋。
矩形
圓形
橢圓形
線條
折線
<polyline> 是一個連線的直線組。由於點的列表可能很長,因此所有點都包含在一個屬性中
xml
<polyline points="60, 110 65, 120 70, 115 75, 130 80, 125 85, 140 90, 135 95, 150 100, 145"/>
points-
點的列表。每個數字必須用空格、逗號、EOL 或帶額外空格的行尾符分隔。每個點必須包含兩個數字:x 座標和 y 座標。因此,列表
(0,0)、(1,1)和(2,2)可以寫成0, 0 1, 1 2, 2。
多邊形
<polygon> 類似於 <polyline>,因為它由連線一系列點的直線段組成。但對於多邊形,路徑會自動連線最後一個點與第一個點,形成一個封閉的形狀。
注意:矩形是一種多邊形,因此可以使用多邊形建立沒有圓角的 <rect/> 元素。
xml
<polygon points="50, 160 55, 180 70, 180 60, 190 65, 205 50, 195 35, 205 40, 190 30, 180 45, 180"/>
points-
點的列表,每個數字用空格、逗號、EOL 或帶額外空格的行尾符分隔。每個點必須包含兩個數字:x 座標和 y 座標。因此,列表
(0,0)、(1,1)和(2,2)可以寫成0, 0 1, 1 2, 2。然後繪製會關閉路徑,因此會從(2,2)到(0,0)繪製最後一條直線。