一、svg的 <path>命令
M = moveto
//
m 50 20 =》 以(50,20)位置為起始點
L = lineto // m 50 20 l 20 50 =》從(50,20)到(20,50)作直線
H = horizontal lineto // m 50 20 h 50 =》 從(50,20)到(50,50)繪制一條平行線
V = vertical lineto // m 50 20 v 50 =》 從(50,20)到(100,20)繪制一條垂直線
C = curveto
S = smooth curveto
Q = quadratic Bézier curve
T = smooth quadratic Bézier curveto
A = elliptical Arc
Z = closepath // 結束路徑,回到原點
L = lineto // m 50 20 l 20 50 =》從(50,20)到(20,50)作直線
H = horizontal lineto // m 50 20 h 50 =》 從(50,20)到(50,50)繪制一條平行線
V = vertical lineto // m 50 20 v 50 =》 從(50,20)到(100,20)繪制一條垂直線
C = curveto
S = smooth curveto
Q = quadratic Bézier curve
T = smooth quadratic Bézier curveto
A = elliptical Arc
Z = closepath // 結束路徑,回到原點
注意:以上所有命令均允許小寫字母。大寫表示絕對定位,小寫表示相對定位。
二、svg的 <path>語法
1. 語法 <path d="M10 10 H 90 V 90 M100 100 H 180 V 180 H 100" stroke="blue" stroke-width="2" /> ; 其中 d 引出路徑
2. d 以M絕對定位開頭,則后面的m相對於前一個M/m
示例: <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200" height="200"> <path d="M20 20 m 0 0 h 320 m -320 0 m 0 20 h 320 m -320 0 m 0 20 h 320" stroke="blue" stroke-width="2" /> </svg>
解析:
- M 20 20是第一個起始點
- m 0 0相對於M 20 20
- m -320 0 相對於 m 0 0
- 以此類推...
三、js動態添加svg的<path>
let nameSpace = 'http://www.w3.org/2000/svg'; //定義命名空間 var barChart = document.createElementNS(nameSpace,'svg'); //在html里定義一個svg barChart.setAttribute('width', barChartWidth); //添加長寬 barChart.setAttribute('height', barChartHeight); let svgWrap = document.querySelector("#svg-wrapper"); //在id名為svg-wrapper的div里添加此svg svgWrap.appendChild(barChart); //水平分區線 let hSectionLine = document.createElementNS(nameSpace, "path"); //在svg里添加一個path let hSectionLinePath = ""; for (let i = 0; i < vScaleNum; i++) { hSectionLinePath = hSectionLinePath + " m 0" + (-vScaleSpacing * radtio) + " h " + hLength + " m " + (-hLength) + " 0"; } // 得到的是一個累加的多重定向path let hSectionLinesPath = zeroPoint + hSectionLinePath; console.log(hSectionLinesPath); // 類似M20 20 m 0 0 h 320 m -320 0 m 0 20 h 320 m -320 0 m 0 20 h 320 hSectionLine.setAttribute("d", hSectionLinesPath); //給path新增一個屬性,即路徑d hSectionLine.setAttribute("stroke", hSectionLineColor); //給path一個顏色 barChart.appendChild(hSectionLine); //添加至svg節點里
———— 待續 ————
