Chapter 34: SVG in HTML

SVG Lines and Paths

Mastering vector strokes, `<polyline>`, `<polygon>`, and the complete `<path>` command dictionary from Bézier curves to elliptical arcs.

LEARNING OBJECTIVES
  • Implement straight multi-segment vectors using <line>, <polyline>, and <polygon>.
  • Understand the difference between Absolute (Uppercase) and Relative (Lowercase) <path> commands.
  • Master the complete SVG <path> command dictionary: M, L, H, V, C, S, Q, T, A, and Z.
  • Deconstruct complex cubic Bézier curves and elliptical arc parameters (rx ry x-rot large-arc sweep x y).
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

📖 The Mental Model & Story (Intuitive Foundation)

Imagine programming a robotic vector pen plotter to draw on a sheet of drafting paper:

  • You lower the pen onto the paper at an exact coordinate $\to$ M (MoveTo).
  • You glide the pen in a straight line to a new point $\to$ L (LineTo).
  • You pull two invisible magnetic handles to warp the ink into an organic curve $\to$ C (Cubic Bézier).
  • You spin an elliptical compass between two anchor points $\to$ A (Elliptical Arc).
  • You draw a clean straight line back to where you first touched the paper $\to$ Z (ClosePath).
THE PEN PLOTTER COMMAND MODEL:
  M 20,80    -> Pick up pen, move to (20, 80) without drawing
  L 80,20    -> Draw straight line to (80, 20)
  C 90,0 130,0 140,20 -> Draw smooth wave using 2 control handles
  A 30,30 0 0,1 180,80 -> Draw circular arc
  Z          -> Snap straight line back to start (20, 80)

The <path> element is the ultimate Swiss Army Knife of vector graphics. Every shape—from simple triangles and geometric stars to typography fonts and photorealistic character vectors—can be expressed through <path d="...">.


Technical Deep Dive & Specifications

1. Straight-Line Primitives: <line>, <polyline>, and <polygon>

Element Syntax & Attributes Behavior
<line> <line x1="10" y1="10" x2="90" y2="90" stroke="#fff" /> Draws a single straight line segment between $(x_1, y_1)$ and $(x_2, y_2)$.
<polyline> <polyline points="10,10 40,60 80,30 120,90" fill="none" stroke="#fff" /> Connects an open series of coordinate vertices. Does not close the path back to the start.
<polygon> <polygon points="100,10 40,198 190,78 10,78 160,198" fill="#f59e0b" /> Connects a series of points and automatically closes the last point back to the first point with a straight line.

2. The Complete <path> Command Dictionary

Path data is defined in the d attribute string: <path d="..." />.

The Capitalization Rule:

  • UPPERCASE commands (M, L, C, A...) = Absolute Coordinates (e.g. L 100 200 means move to absolute coordinate $(100, 200)$ on the canvas).
  • LOWERCASE commands (m, l, c, a...) = Relative Coordinates (e.g. l 100 200 means move $+100$ units right and $+200$ units down from the current pen location).
+---------------------------------------------------------------------------------------------------+
|                                 THE SVG <path> COMMAND DICTIONARY                                 |
+---------------------------------------------------------------------------------------------------+
  Command      Name                       Parameters                          Function
  ─────────────────────────────────────────────────────────────────────────────────────────────────
  M / m        MoveTo                     (x y)                               Picks up pen; sets new start coordinate
  L / l        LineTo                     (x y)                               Draws straight line to (x, y)
  H / h        Horizontal LineTo          (x)                                 Draws straight horizontal line
  V / v        Vertical LineTo            (y)                                 Draws straight vertical line
  C / c        Cubic Bézier               (x1 y1, x2 y2, x y)                 Draws cubic curve with 2 control points
  S / s        Smooth Cubic Bézier        (x2 y2, x y)                        Reflects previous control point + 1 new point
  Q / q        Quadratic Bézier           (x1 y1, x y)                        Draws quadratic curve with 1 control point
  T / t        Smooth Quadratic Bézier    (x y)                               Reflects previous quadratic control point
  A / a        Elliptical Arc             (rx ry x-rot large-arc sweep x y)   Draws elliptical arc between points
  Z / z        ClosePath                  (none)                              Draws straight line back to start of subpath

3. Understanding Bézier Curves (C, S, Q, T)

CUBIC BÉZIER (C x1 y1, x2 y2, x y):         QUADRATIC BÉZIER (Q x1 y1, x y):
       (x1,y1)            (x2,y2)                          (x1,y1) Control
          o                  o                                    o
         /                    \                                 /   \
        /    . - - - - - .     \                               /  . - . \
       * '                 ' *                                * '       ' *
    Start                    End                           Start          End
    (Current Pos)           (x, y)                         (Current Pos)  (x, y)
  • Cubic Bézier (C): Provides two independent control handles $(x_1, y_1)$ and $(x_2, y_2)$ before terminating at $(x, y)$. This allows $S$-shaped and organic curves.
  • Smooth Cubic (S): Assumes the first control handle is the direct mirror reflection of the previous curve's second handle, ensuring a continuous smooth derivative.
  • Quadratic Bézier (Q): Uses a single shared control handle $(x_1, y_1)$ to pull the midpoint into a parabolic arc.

4. Deconstructing the Elliptical Arc Command (A)

The Arc command is the most powerful and parameter-dense command in SVG:

$$\text{A } rx\enspace ry\enspace \text{x-axis-rotation}\enspace \text{large-arc-flag}\enspace \text{sweep-flag}\enspace x\enspace y$$

A  30  20    0    0    1    100  150
   ──┬───    ─    ─    ─    ───┬────
     │       │    │    │       └─ End Coordinate (x, y)
     │       │    │    └───────── Sweep Flag: 0 = Anti-clockwise, 1 = Clockwise
     │       │    └────────────── Large Arc Flag: 0 = Shortest arc (≤180°), 1 = Longest arc (>180°)
     │       └─────────────────── X-Axis Rotation: Rotation angle of the ellipse in degrees
     └─────────────────────────── Radii: rx = Horizontal radius, ry = Vertical radius

💻 Interactive Code Playground

Starter Code

Line-by-Line Code Breakdown

  • Line 57: <polygon points="100,10 126,68 ..."/> defines a five-pointed star by specifying ten $(x, y)$ coordinate pairs. The browser automatically joins point 10 back to point 1.
  • Line 72: <path d="M 10,100 C 40,30 70,30 100,100 S 160,170 190,100".../> starts at $(10, 100)$, draws a crest using cubic control points $(40, 30)$ and $(70, 30)$, and uses the smooth command S to draw the mirrored trough to $(190, 100)$.
  • Line 87: <path d="M 100,100 L 170,100 A 70 70 0 0 0 100,30 Z".../> creates a $90^\circ$ circular pie slice: moves to center $(100, 100)$, lines to $(170, 100)$, draws a $70\text{px}$ radius arc counter-clockwise (sweep=0) to $(100, 30)$, and closes back to center (Z).

Expected Browser Render Output


SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL playground.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...
+---------------------------------------------------------------+
|  1. Geometric Star       2. Bézier Wave        3. Arc Wedge   |
|         /\                   . - .                  /|        |
|     /--/  \--\             /       \               / | Arc    |
|       \    /              *---------*             +--+        |
|       /    \                       \        /     (Pie Slice) |
|      /--/\--\                       ' - - '                   |
+---------------------------------------------------------------+

🏋️ Hands-On Exercise

🎯 The Challenge: Hand-Craft a Weather Cloud & Lightning Icon

Objective: Hand-craft an authentic SVG weather icon using pure <path d="..."> command strings without external graphics editors.

Instructions:

  1. Create an SVG with viewBox="0 0 200 200".
  2. Construct the cloud body path using:
    • M 50,130 (Start at bottom-left base)
    • H 150 (Draw flat bottom line to $X=150$)
    • A 25 25 0 0 0 160,85 (Draw right cloud puff arc)
    • A 35 35 0 0 0 105,65 (Draw top main cloud puff arc)
    • A 25 25 0 0 0 50,130 (Draw left cloud puff arc)
    • Z (Close path)
  3. Underneath the cloud, draw a sharp zigzag lightning bolt using <polygon points="95,140 115,140 100,165 120,165 85,195 95,170 80,170" fill="#facc15"/>.

🏁 Starter Code Sandbox

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
STARTER CODE SANDBOX exercise.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

⚠️ Common Pitfalls

  1. Mixing up Uppercase vs Lowercase Commands: Writing l 50 50 (relative: move $+50\text{px}$ from current position) when you intended L 50 50 (absolute: jump to canvas coordinate $50, 50$) is the #1 cause of broken vector path rendering.
  2. Arc Flag Confusion (large-arc & sweep): If your arc bulges inward instead of outward, flip the sweep-flag between 0 and 1. If your arc takes the long way around ($>180^\circ$) instead of the short route, toggle the large-arc-flag from 1 to 0.
  3. Unclosed Polyline Fills: <polyline> does not automatically join the last point to the start. If you add a fill to a <polyline>, the browser fills the interior, but the stroke border remains open. Use <polygon> or <path ... Z> if you need a fully closed stroke boundary.

💡 Pro Tips

  1. Path Minification (Omission of Redundant Command Letters): In SVG path syntax, if multiple consecutive segments use the same command, you can omit the repeated letter. For example, L 10 20 L 30 40 L 50 60 can be condensed to L 10 20 30 40 50 60.
  2. The H and V Optimization: Whenever a line is strictly horizontal or vertical, replace L 150 50 with H 150 (if only $X$ changes) or V 50 (if only $Y$ changes). This shaves bytes off your SVG payload.

📌 Key Takeaways

  • <line>, <polyline>, <polygon>: Primitives for straight lines; <polygon> automatically closes the perimeter, while <polyline> remains an open stroke.
  • Case Sensitivity: Uppercase letters (M, L, C, A) operate on Absolute canvas coordinates; lowercase letters (m, l, c, a) operate on Relative deltas.
  • Cubic Béziers (C): Form curves using two control handles $(x_1, y_1)$ and $(x_2, y_2)$ before the destination $(x, y)$.
  • Elliptical Arcs (A): Require 7 arguments: $rx, ry$, X-rotation, large-arc-flag, sweep-flag, and destination $x, y$.
  • Z: Always draws a straight connecting stroke back to the beginning of the current subpath.
  • --
⭐ LEARN: HTML 🌟 ⚔️ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

What is the difference between L 50 100 and l 50 100 in an SVG <path> definition?

Question 1 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 2 / 3

Which path command terminates the current subpath by drawing a straight line back to the initial M coordinate?

Question 2 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 3 / 3

In the arc command A rx ry x-rot large-arc sweep x y, what does setting sweep-flag = 1 specify?

Question 3 / 3 Topic: HTML Fundamentals
00:45 REMAINING
XP REWARD
+250 XP