乐闻世界logo
搜索文章和话题

How to understand and use SVG path commands

2月21日 15:19

SVG paths are the most powerful and flexible elements in SVG, defined using the <path> tag and d attribute. Path commands consist of letters and numbers, and can be categorized as follows:

1. Move Commands (M, m)

  • M x y: Move to absolute coordinates (x, y)
  • m dx dy: Move to relative coordinates (relative to current position)
  • Purpose: Start a new path segment without drawing lines

2. Line Commands (L, l, H, h, V, v)

  • L x y: Draw line to absolute coordinates (x, y)
  • l dx dy: Draw line to relative coordinates
  • H x: Horizontal line to absolute x coordinate
  • h dx: Horizontal line to relative x coordinate
  • V y: Vertical line to absolute y coordinate
  • v dy: Vertical line to relative y coordinate

3. Curve Commands Cubic Bézier Curves (C, c, S, s)

  • C x1 y1, x2 y2, x y: Draw to (x,y) using two control points (x1,y1) and (x2,y2)
  • c dx1 dy1, dx2 dy2, dx dy: Relative coordinate version
  • S x2 y2, x y: Smooth curve, automatically infers first control point
  • s dx2 dy2, dx dy: Relative coordinate version

Quadratic Bézier Curves (Q, q, T, t)

  • Q x1 y1, x y: Draw to (x,y) using one control point (x1,y1)
  • q dx1 dy1, dx dy: Relative coordinate version
  • T x y: Smooth curve, automatically infers control point
  • t dx dy: Relative coordinate version

Elliptical Arc (A, a)

  • A rx ry x-axis-rotation large-arc-flag sweep-flag x y
  • Parameters: rx, ry (ellipse radii), x-axis-rotation (rotation angle), large-arc-flag (large arc flag), sweep-flag (drawing direction), x, y (end coordinates)

4. Close Path Commands (Z, z)

  • Z or z: Close path, connect to starting point
  • Automatically draws a straight line back to the start

Example Path:

svg
<svg viewBox="0 0 100 100"> <!-- Heart shape path --> <path d="M 50 90 C 20 60, 0 30, 30 30 C 40 30, 50 40, 50 50 C 50 40, 60 30, 70 30 C 100 30, 80 60, 50 90 Z" fill="red" /> </svg>

Best Practices:

  • Uppercase letters indicate absolute coordinates, lowercase letters indicate relative coordinates
  • Spaces and commas between command letters can be omitted
  • Consecutive same commands can omit the command letter
  • Using relative coordinates can simplify path definitions
标签:SVG