SVG即Scalable Vector Graphics可縮放矢量圖形,使用XML格式定義圖形, 主要優勢在於可縮放的同時不會影響圖片的質量。
SVG 在html 中常用的方法
1.使用<img>元素來嵌入SVG圖像
<img src=”http://www.w3school.com.cn/svg/rect1.svg” width=”300″ />
2.將SVG圖像作為背景圖像嵌入
background: url(‘http://www.w3school.com.cn/svg/rect1.svg’) no-repeat;
3.使用svg元素,通過代碼將SVG圖像嵌入到HTML代碼中
<svg width=”100%” height=”100%”> <rect x=”20″ y=”20″ width=”250″ height=”250″style=”fill:#fecdddd;”/> </svg>
兼容性
IE 9~11 Firefox 40 + Chrome 43+ Safari 8+ Opera 32+
svg sprites
svg sprites類似於css sprites,將各個svg合並在一起。
最主要的優點就是能減少頁面的加載時間,優化開發流程,以及保持頁面中圖片元素的一致性。
實踐中我們可以把整塊的svg放在head頭部, 因此可以在一處地方更新svg即可,而不是讓svg的代碼塊散落在文檔的各個地方。
<head> <meta charset=”utf-8″ /> <title>svg</title> <svg version=”1.1″ xmlns=”http://www.w3.org/2000/svg” xmlns:xlink=”http://www.w3.org/1999/xlink” width=”32″ height=”158″ viewBox=”0 0 32 158″> <!– SVG等省略 –> </svg> </head>
SVG形狀
矩形 <rect>
<rect x=”20″ y=”20″ rx=”20″ ry=”20″ width=”250″ height=”100″ style=”fill:red;stroke:black; stroke-width:5;opacity:0.5″/>
解釋:x為x坐標,y為y坐標;width 和 height 分別為形狀的高度和寬度;rx 和 ry 屬性可使矩形產生圓角。
屬性: fill 屬性定義形狀的填充顏色
stroke 屬性定義圖形邊框的顏色
stroke-width 屬性定義形狀邊框的寬度
圓形 <circle>
<circle cx=”100″ cy=”50″ r=”40″ stroke=”black” stroke-width=”2″ fill=”red”/>
解釋:cx 和 cy分別為圓點的 x 和 y 坐標;r為半徑。
橢圓<ellipse>
<ellipse cx=”300″ cy=”150″ rx=”200″ ry=”80″ style=”fill:rgb(200,100,50); stroke:rgb(0,0,100);stroke-width:2″/>
解釋:cx 圓點的 x 坐標,cy 圓點的 y 坐標;rx 水平半徑,ry 垂直半徑。
線<line>
<line x1=”0″ y1=”0″ x2=”300″ y2=”300″ style=”stroke:rgb(99,99,99);stroke-width:2″/>
解釋:(x1,y1)為線條的開始坐標;(x2,y2)為線條的結束坐標。
折線<polyline>
<polyline points=”0,0 0,20 20,20 20,40 40,40 40,60″ style=”fill:white;stroke:red;stroke-width:2″/>
解釋:points 屬性定義多邊形每個角的 x 和 y 坐標。為了可讀性,建議x與y坐標用逗號分開,每個角之間的坐標用空格分開。
多邊形<polygon>
<polygon points=”220,100 300,210 170,250″ style=”fill:#cccccc; stroke:#000000;stroke-width:1″/>
解釋:points 屬性定義多邊形每個角的 x 和 y 坐標。
路徑<path>
直線指令:
M = moveto
L = lineto
H = horizontal lineto
V = vertical lineto
Z = closepath
注釋:以上所有命令均允許小寫字母。大寫表示絕對定位,小寫表示相對定位。
<svg>
<path d=”M250 150 L150 350 L350 350 Z” />
</svg>
解釋:該路徑開始於位置 250 150,到達位置 150 350,然后從那里開始到 350 350,最后在 250 150 關閉路徑。
由於繪制路徑的復雜性,建議使用 SVG 編輯器來創建復雜的圖形。
svg的貝塞爾曲線
貝塞爾曲線指令:
C = curveto
S = smooth curveto
Q = quadratic Belzier curve
T = smooth quadratic Belzier curveto
C三次貝塞爾曲線
C x1 y1, x2 y2, x y (or c dx1 dy1, dx2 dy2, dx dy)
S光滑三次貝塞爾曲線
S x2 y2, x y (or s dx2 dy2, dx dy)
Q二次貝塞爾曲線
Q x1 y1, x y (or q dx1 dy1, dx dy)
T光滑二次貝塞爾曲線
T x y (or t dx dy)