SVG <path>

SVG 路徑 - <path>

<path> 元素用于定義路徑。

以下命令可用于路徑數據:

  • M = moveto(移動到)
  • L = lineto(畫線到)
  • H = horizontal lineto(水平線到)
  • V = vertical lineto(垂直線到)
  • C = curveto(曲線到)
  • S = smooth curveto(平滑曲線到)
  • Q = quadratic Bézier curve(二次貝塞爾曲線)
  • T = smooth quadratic Bézier curveto(平滑二次貝塞爾曲線)
  • A = elliptical Arc(橢圓弧)
  • Z = closepath(閉合路徑)

注意:以上所有命令也可以用小寫字母表示。大寫字母表示絕對定位,小寫字母表示相對定位。

例子 1

下面的例子定義了一個路徑,起始位置為 150,0,然后畫一條線到 75,200 的位置,接著從那里畫一條線到 225,200 的位置,最后閉合路徑回到 150,0。

這是 SVG 代碼:

<svg height="210" width="400">
  <path d="M150 0 L75 200 L225 200 Z" />
</svg>

親自試一試

例子 2

貝塞爾曲線(Bézier curves)用于建模可無限縮放的平滑曲線。通常,用戶選擇兩個端點和一或兩個控制點。有一個控制點的貝塞爾曲線稱為二次貝塞爾曲線(quadratic Bézier curve),有兩個控制點的貝塞爾曲線稱為三次貝塞爾曲線(cubic)。

下例創建一條二次貝塞爾曲線,其中 A 和 C 是起點和終點,B 是控制點:

A B C

這是 SVG 代碼:

<svg height="400" width="450">
  <path id="lineAB" d="M 100 350 l 150 -300" stroke="red" stroke-width="3" fill="none" />
  <path id="lineBC" d="M 250 50 l 150 300" stroke="red" stroke-width="3" fill="none" />
  <path d="M 175 200 l 150 0" stroke="green" stroke-width="3" fill="none" />
  <path d="M 100 350 q 150 -300 300 0" stroke="blue" stroke-width="5" fill="none" />
  <!-- 標記相關的點 -->
  <g stroke="black" stroke-width="3" fill="black">
    <circle id="pointA" cx="100" cy="350" r="3" />
    <circle id="pointB" cx="250" cy="50" r="3" />
    <circle id="pointC" cx="400" cy="350" r="3" />
  </g>
  <!-- 給點添加標簽 -->
  <g font-size="30" font-family="sans-serif" fill="black" stroke="none"
  text-anchor="middle">
    <text x="100" y="350" dx="-30">A</text>
    <text x="250" y="50" dy="-10">B</text>
    <text x="400" y="350" dx="30">C</text>
  </g>
</svg>

親自試一試

很復雜吧?是的!!!由于繪制路徑非常復雜,強烈建議使用 SVG 編輯器來創建復雜圖形。