部分參考(Copy):[http://www.ruanyifeng.com/blog/2018/08/svg.html](http://www.ruanyifeng.com/blog/2018/08/svg.html)
[TOC]
>[success]這里記錄下 svg 的一些 API,主要想探索下用 svg 實現一些 CSS 不好實現的圖案及動畫效果。
# 如何在項目中使用 svg
1.SVG 文件可以直接插入網頁,成為 DOM 的一部分,然后用 JavaScript 和 CSS 進行操作。
```html
<!DOCTYPE html>
<html>
<head></head>
<body>
<svg
id="mysvg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 800 600"
preserveAspectRatio="xMidYMid meet"
>
<circle id="mycircle" cx="400" cy="300" r="50" />
<svg>
</body>
</html>
```
2.SVG 代碼也可以寫在一個獨立文件中,然后用`<img>`、`<object>`、`<embed>`、`<iframe>`等標簽插入網頁。
```html
<img src="circle.svg">
<object id="object" data="circle.svg" type="image/svg+xml"></object>
<embed id="embed" src="icon.svg" type="image/svg+xml">
<iframe id="iframe" src="icon.svg"></iframe>
```
3.CSS 也可以使用 SVG 文件。
```css
.logo {
background: url(icon.svg);
}
```
4.SVG 文件還可以轉為 BASE64 編碼,然后作為 Data URI 寫入網頁。
```html
<img src="data:image/svg+xml;base64,[data]">
```
# 語法
## \<svg> 標簽
```html
<svg width="100%" height="100%">
<circle id="mycircle" cx="50" cy="50" r="50" />
</svg>
```
`<svg>`的`width`屬性和`height`屬性,指定了 SVG 圖像在 HTML 元素中所占據的寬度和高度。除了相對單位,也可以采用絕對單位(單位:像素)。如果不指定這兩個屬性,SVG 圖像默認大小是300像素(寬) x 150像素(高)。
如果只想展示 SVG 圖像的一部分,就要指定`viewBox`屬性(如果是 XML 文件注意大小寫 viewbox != viewBox)
```html
<svg width="100" height="100" viewBox="50 50 50 50">
<circle id="mycircle" cx="50" cy="50" r="50" />
</svg>
```
`<viewBox>`屬性的值有四個數字,分別是左上角的橫坐標和縱坐標、視口的寬度和高度。上面代碼中,SVG 圖像是100 像素寬 x 100 像素高,`viewBox`屬性指定視口從`(50, 50)`這個點開始。所以,實際看到的是右下角的四分之一圓。
注意,視口必須適配所在的空間。上面代碼中,視口的大小是 50 x 50,由于 SVG 圖像的大小是 100 x 100,所以視口會放大去適配 SVG 圖像的大小,即放大了四倍。
如果不指定`width`屬性和`height`屬性,只指定`viewBox`屬性,則相當于只給定 SVG 圖像的長寬比。這時,SVG 圖像的默認大小將等于所在的 HTML 元素的大小。

- width、height:控制的是視窗
- SVG 代碼定義 SVG 世界
- viewBox,preserveAspectRatio 控制我們的視野
## \<circle> 標簽
```html
<svg width="300" height="180">
<circle cx="30" cy="50" r="25" />
<circle cx="90" cy="50" r="25" class="red" />
<circle cx="150" cy="50" r="25" class="fancy" />
</svg>
```

上面的代碼定義了三個圓。`<circle>`標簽的`cx`、`cy`、`r`屬性分別為橫坐標、縱坐標和半徑,單位為像素。坐標都是相對于`<svg>`畫布的左上角原點。

`class`屬性用來指定對應的 CSS 類
```css
.red {
fill: red;
}
.fancy {
fill: none;
stroke: black;
stroke-width: 3pt;
}
```
SVG 的 CSS 屬性與網頁元素有所不同。
- fill:填充色
- stroke:描邊色
- stroke-width:邊框寬度
## \<line> 標簽
```html
<svg width="300" height="180">
<line x1="0" y1="0" x2="200" y2="0" style="stroke:rgb(0,0,0);stroke-width:5" />
</svg>
```
上面代碼中,`<line>`標簽的`x1`屬性和`y1`屬性,表示線段起點的橫坐標和縱坐標;`x2`屬性和`y2`屬性,表示線段終點的橫坐標和縱坐標;`style`屬性表示線段的樣式。
## \<polyline> 標簽
`<polyline>`標簽用于繪制一根折線。
```html
<svg width="300" height="180">
<polyline points="3,3 30,28 3,53" fill="#ccc" stroke="black" />
</svg>
```

`<polyline>`的`points`屬性指定了每個端點的坐標,橫坐標與縱坐標之間與逗號分隔,點與點之間用空格分隔。
## \<rect> 標簽
```html
<svg width="300" height="180">
<rect x="0" y="0" height="100" width="200" style="stroke: #70d5dd; fill: #dd524b" />
</svg>
```

`<rect>`的`x`屬性和`y`屬性,指定了矩形左上角端點的橫坐標和縱坐標;`width`屬性和`height`屬性指定了矩形的寬度和高度(單位像素)。

## \<ellipse> 標簽
ellipse 標簽用于繪制橢圓。
```html
<svg width="300" height="180">
<ellipse cx="60" cy="60" ry="40" rx="20"
stroke="skyblue" stroke-width="5" fill="#58a"/>
</svg>
```

`<ellipse>`的`cx`屬性和`cy`屬性,指定了橢圓中心的橫坐標和縱坐標(單位像素);`rx`屬性和`ry`屬性,指定了橢圓橫向軸和縱向軸的半徑(單位像素)。

## \<polygon> 標簽
polygon 標簽用于繪制多邊形。
```html
<svg width="300" height="180">
<polygon fill="#58a" stroke="skyblue"
stroke-width="3" points="50,0 150,0 180,100 20,100"/>
</svg>
```

`<polygon>`的`points`屬性指定了每個端點的坐標,橫坐標與縱坐標之間與逗號分隔,點與點之間用空格分隔。
## \<path> 標簽
path 用于繪制路徑。
```html
<svg width="300" height="180">
<path d="
M 18,3
L 46,3
L 46,40
L 61,40
L 32,68
L 3,40
L 18,40
Z
"></path>
</svg>
```

`<path>`的`d`屬性表示繪制順序,它的值是一個長字符串,每個字母表示一個繪制動作,后面跟著坐標。
- M:移動到(moveto)
- L:畫直線到(lineto)
- Z:閉合路徑
## \<text> 標簽
text 標簽用于繪制文本。
```html
<svg width="300" height="180">
<text x="50" y="25">Hello World</text>
</svg>
```
`<text>`的`x`屬性和`y`屬性,表示文本區塊基線(baseline)起點的橫坐標和縱坐標。文字的樣式可以用`class`或`style`屬性指定。
## \<use> 標簽
use 標簽用于復制一個形狀。
```html
<svg width="300" height="300">
<circle id="myCircle" cx="5" cy="5" r="4"/>
<use href="#myCircle" x="10" y="0" fill="blue" />
<use href="#myCircle" x="20" y="0" fill="white" stroke="blue" />
</svg>
```

`<use>`的`href`屬性指定所要復制的節點,`x`屬性和`y`屬性是`<use>`左上角的坐標。另外,還可以指定`width`和`height`坐標。
## \<g> 標簽
g 標簽用于將多個形狀定義成一個組,方便復用。
```html
<svg width="300" height="100">
<g id="myCircle">
<text x="25" y="20">圓形</text>
<circle cx="50" cy="50" r="20"/>
</g>
<use href="#myCircle" x="100" y="0" fill="blue" />
<use href="#myCircle" x="200" y="0" fill="white" stroke="blue" />
</svg>
```
## \<defs> 標簽
`<defs>`標簽用于自定義形狀,它內部的代碼不會顯示,僅供引用。
```html
<svg width="300" height="100">
<defs>
<g id="myCircle">
<text x="25" y="20">圓形</text>
<circle cx="50" cy="50" r="20"/>
</g>
</defs>
<use href="#myCircle" x="0" y="0" />
<use href="#myCircle" x="100" y="0" fill="blue" />
<use href="#myCircle" x="200" y="0" fill="white" stroke="blue" />
</svg>
```
## \<pattern> 標簽
`<pattern>`標簽用于自定義一個形狀,該形狀可以被引用來平鋪一個區域。
```html
<svg width="500" height="500">
<defs>
<pattern id="dots" x="0" y="0" width="100" height="100" patternUnits="userSpaceOnUse">
<circle fill="#bee9e8" cx="50" cy="50" r="35" />
</pattern>
</defs>
<rect x="0" y="0" width="100%" height="100%" fill="url(#dots)" />
</svg>
```

上面代碼中,`<pattern>`標簽將一個圓形定義為`dots`模式。`patternUnits="userSpaceOnUse"`表示`<pattern>`的寬度和長度是實際的像素值。然后,指定這個模式去填充下面的矩形。
## \<image> 標簽
`<image>`標簽用于插入圖片文件。
```html
<svg viewBox="0 0 100 100" width="100" height="100">
<image xlink:href="path/to/image.jpg"
width="50%" height="50%"/>
</svg>
```
上面代碼中,`<image>`的`xlink:href`屬性表示圖像的來源。
## \<animate> 標簽
`<animate>`標簽用于產生動畫效果。
```html
<svg width="500px" height="500px">
<rect x="0" y="0" width="100" height="100" fill="#feac5e">
<animate attributeName="x" from="0" to="500" dur="2s" repeatCount="indefinite" />
</rect>
</svg>
```
上面代碼中,矩形會不斷移動,產生動畫效果。
`<animate>`的屬性含義如下。
- attributeName:發生動畫效果的屬性名。
- from:單次動畫的初始值。
- to:單次動畫的結束值。
- dur:單次動畫的持續時間。
- repeatCount:動畫的循環模式。
可以在多個屬性上面定義動畫。
```html
<animate attributeName="x" from="0" to="500" dur="2s" repeatCount="indefinite" />
<animate attributeName="width" to="500" dur="2s" repeatCount="indefinite" />
```
## \<animateTransform> 標簽
`<animate>`標簽對 CSS 的`transform`屬性不起作用,如果需要變形,就要使用`<animateTransform>`標簽。
```html
<svg width="500px" height="500px">
<rect x="250" y="250" width="50" height="50" fill="#4bc0c8">
<animateTransform
attributeName="transform" type="rotate" begin="0s" dur="10s"
from="0 200 200" to="360 400 400" repeatCount="indefinite" />
</rect>
</svg>
```

上面代碼中,`<animateTransform>`的效果為旋轉(`rotate`),這時`from`和`to`屬性值有三個數字,第一個數字是角度值,第二個值和第三個值是旋轉中心的坐標。`from="0 200 200"`表示開始時,角度為0,圍繞`(200, 200)`開始旋轉;`to="360 400 400"`表示結束時,角度為360,圍繞`(400, 400)`旋轉。
# JavaScript 操作 svg
如果 SVG 代碼直接寫在 HTML 網頁之中,它就成為網頁 DOM 的一部分,可以直接用 DOM 操作。
```html
<svg
id="mysvg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 800 600"
preserveAspectRatio="xMidYMid meet"
>
<circle id="mycircle" cx="400" cy="300" r="50" />
<svg>
```
```js
var mycircle = document.getElementById('mycircle');
mycircle.addEventListener('click', function(e) {
console.log('circle clicked - enlarging');
mycircle.setAttribute('r', 60);
}, false);
```
- 創建圖形:document.createElementNS(ns, tagName)
- 添加圖形:element.appendChild(childElement)
- 設置、獲取屬性:element.setAttribute(name, value), element.getAttribute(name)
# SVG 圖像轉換為 Canvas 圖像
首先,需要新建一個`Image`對象,將 SVG 圖像指定到該`Image`對象的`src`屬性。
```js
var img = new Image();
var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
var DOMURL = self.URL || self.webkitURL || self;
var url = DOMURL.createObjectURL(svg);
img.src = url;
```
然后,當圖像加載完成后,再將它繪制到`<canvas>`元素。
```js
img.onload = function () {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
};
```
# 實例
- 序言 & 更新日志
- H5
- Canvas
- 序言
- Part1-直線、矩形、多邊形
- Part2-曲線圖形
- Part3-線條操作
- Part4-文本操作
- Part5-圖像操作
- Part6-變形操作
- Part7-像素操作
- Part8-漸變與陰影
- Part9-路徑與狀態
- Part10-物理動畫
- Part11-邊界檢測
- Part12-碰撞檢測
- Part13-用戶交互
- Part14-高級動畫
- CSS
- SCSS
- codePen
- 速查表
- 面試題
- 《CSS Secrets》
- SVG
- 移動端適配
- 濾鏡(filter)的使用
- JS
- 基礎概念
- 作用域、作用域鏈、閉包
- this
- 原型與繼承
- 數組、字符串、Map、Set方法整理
- 垃圾回收機制
- DOM
- BOM
- 事件循環
- 嚴格模式
- 正則表達式
- ES6部分
- 設計模式
- AJAX
- 模塊化
- 讀冴羽博客筆記
- 第一部分總結-深入JS系列
- 第二部分總結-專題系列
- 第三部分總結-ES6系列
- 網絡請求中的數據類型
- 事件
- 表單
- 函數式編程
- Tips
- JS-Coding
- Framework
- Vue
- 書寫規范
- 基礎
- vue-router & vuex
- 深入淺出 Vue
- 響應式原理及其他
- new Vue 發生了什么
- 組件化
- 編譯流程
- Vue Router
- Vuex
- 前端路由的簡單實現
- React
- 基礎
- 書寫規范
- Redux & react-router
- immutable.js
- CSS 管理
- React 16新特性-Fiber 與 Hook
- 《深入淺出React和Redux》筆記
- 前半部分
- 后半部分
- react-transition-group
- Vue 與 React 的對比
- 工程化與架構
- Hybird
- React Native
- 新手上路
- 內置組件
- 常用插件
- 問題記錄
- Echarts
- 基礎
- Electron
- 序言
- 配置 Electron 開發環境 & 基礎概念
- React + TypeScript 仿 Antd
- TypeScript 基礎
- React + ts
- 樣式設計
- 組件測試
- 圖標解決方案
- Storybook 的使用
- Input 組件
- 在線 mock server
- 打包與發布
- Algorithm
- 排序算法及常見問題
- 劍指 offer
- 動態規劃
- DataStruct
- 概述
- 樹
- 鏈表
- Network
- Performance
- Webpack
- PWA
- Browser
- Safety
- 微信小程序
- mpvue 課程實戰記錄
- 服務器
- 操作系統基礎知識
- Linux
- Nginx
- redis
- node.js
- 基礎及原生模塊
- express框架
- node.js操作數據庫
- 《深入淺出 node.js》筆記
- 前半部分
- 后半部分
- 數據庫
- SQL
- 面試題收集
- 智力題
- 面試題精選1
- 面試題精選2
- 問答篇
- 2025面試題收集
- Other
- markdown 書寫
- Git
- LaTex 常用命令
- Bugs