Chapter 34: SVG in HTML

Basic SVG Shapes

Mastering geometric primitives: `<rect>`, `<circle>`, `<ellipse>`, corner radii mathematics, and coordinate origin behaviors.

LEARNING OBJECTIVES
  • Understand the coordinate positioning rules for <rect> (top-left) vs. <circle> and <ellipse> (center origin).
  • Master rounded rectangle corner curvature using the rx and ry radius attributes and radius clamping mechanics.
  • Construct complex geometric UI components using nested <g> (group) containers.
  • Implement pill/capsule shapes, concentric rings, and orbital ellipses purely with geometric primitives.
🎬 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 a mechanical draftsman seated at an architectural drafting board equipped with three precision tools:

  1. The T-Square & Set Square (<rect>): You place the corner of the ruler at a precise point on the drafting paper $(X, Y)$ and measure outward: $W$ units across and $H$ units down. If you swap the hard corner for a curve template, you round off the edges ($rx, ry$).
  2. The Compass (<circle>): You press the metal needle point firmly into the center of the paper $(cx, cy)$ and spin the graphite pencil $r$ units away in a full 360-degree sweep.
  3. The Elliptical Stencil (<ellipse>): You align the center crosshair $(cx, cy)$, but instead of equal radius, you stretch the horizontal radius $rx$ wider than the vertical radius $ry$, producing a stadium oval or planetary ring.
<rect x="50" y="50" w="100" h="60">       <circle cx="100" cy="80" r="40">       <ellipse cx="100" cy="80" rx="60" ry="30">
(50,50) Origin                           (cx,cy) Center Origin                  (cx,cy) Center Origin
  +-------------+                                . - - - .                              . - - - - - - .
  |             |                            '       |       '                      '        |        '
  |             |                          |      (cx,cy)----|-- r = 40           |      (cx,cy)-------|-- rx = 60
  |             |                            '       |       '                      '        |        '
  +-------------+                                ' - - - '                              ' - - - - - - '
                                                                                             | ry = 30

Notice the critical conceptual distinction: Rectangles position from their top-left corner $(x, y)$, while circles and ellipses position from their mathematical center $(cx, cy)$.


Technical Deep Dive & Specifications

1. The <rect> Element (Rectangles & Rounded Boxes)

The <rect> element defines a rectangle aligned with the current coordinate plane.

<rect x="20" y="30" width="200" height="100" rx="15" ry="15" fill="#3b82f6" />

Attribute Specification Matrix:

Attribute Type Default Description
x <length> 0 The X coordinate of the left edge of the rectangle.
y <length> 0 The Y coordinate of the top edge of the rectangle.
width <length> 0 Width of the rectangle (values $\le 0$ disable rendering).
height <length> 0 Height of the rectangle (values $\le 0$ disable rendering).
rx <length> auto Horizontal corner radius. If only rx is provided, ry automatically inherits rx.
ry <length> auto Vertical corner radius. If only ry is provided, rx automatically inherits ry.

Corner Radius Clamping Rule:

According to the W3C SVG 2 Specification, the browser automatically clamps corner radii so that: $$\text{Clamped } rx = \min\left(rx, \frac{\text{width}}{2}\right), \quad \text{Clamped } ry = \min\left(ry, \frac{\text{height}}{2}\right)$$ Setting rx="50%" or rx="9999" on a rectangle creates a perfect pill / stadium capsule shape without manual pixel calculations.


2. The <circle> Element (Equidistant Geometry)

The <circle> element defines a circle based on a single center point and a uniform radial distance.

<circle cx="100" cy="100" r="50" fill="#10b981" stroke="#059669" stroke-width="4" />
Attribute Type Default Description
cx <length> 0 Center X coordinate.
cy <length> 0 Center Y coordinate.
r <length> 0 Radius distance from center (values $\le 0$ disable rendering).

3. The <ellipse> Element (Bi-Axial Curves)

The <ellipse> element defines an ellipse with independent horizontal and vertical radii.

<ellipse cx="150" cy="100" rx="80" ry="40" fill="#8b5cf6" />
Attribute Type Default Description
cx <length> 0 Center X coordinate.
cy <length> 0 Center Y coordinate.
rx <length> 0 Semi-major horizontal radius.
ry <length> 0 Semi-minor vertical radius.

4. Semantic Grouping with <g>

The <g> (group) element acts as a non-rendering structural container (analogous to a <div> in HTML) used to:

  1. Apply collective transformations: transform="translate(100, 50) rotate(45)".
  2. Inherit styles: Attributes placed on <g> (like fill="#ffffff" or stroke-width="2") cascade down to all child shapes.
  3. Structure DOM nodes: Enables clean organization and screen reader semantics.

SYS: ACTIVE
HULL: 98%
CORE: STABLE
NET: ONLINE
HTML STARSHIP CODE TERMINAL example.html
LIVE RENDER & DIAGNOSTICS CORE TEMP: 45°C
INSPECTING DOM: VALID
TAGS: SCANNING...

💻 Interactive Code Playground

Starter Code

Line-by-Line Code Breakdown

  • Line 57–63: <g id="rectangles"...> groups rectangles together. The pill rectangle uses rx="25" which equals exactly half its height ($50 / 2 = 25$), creating perfectly semicircular rounded caps on both ends.
  • Line 66–71: <g id="target-circles"> stacks concentric circles by sharing the same center coordinates cx="270" cy="110", with decreasing radii ($r = 70, 50, 30, 10$).
  • Line 74–82: Demonstrates group translation: <g id="planetary-system" transform="translate(460, 110)"> shifts the local origin $(0, 0)$ to coordinate $(460, 110)$. The planetary ellipse <ellipse cx="0" cy="0" rx="90" ry="30"/> is defined cleanly around its local center.

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...
+---------------------------------------------------------------+
|  SVG Geometric Primitives Gallery                             |
|                                                               |
|  [Sharp Rect]         ( ( ( O ) ) )        \   (Planet)   /   |
|  (Pill Capsule)      Concentric Target       \ (Orbit)  /     |
|                                                (Ellipse)      |
+---------------------------------------------------------------+

🏋️ Hands-On Exercise

🎯 The Challenge: Construct a Space Exploration Mission Patch

Objective: Hand-craft an SVG space mission emblem using ONLY <rect>, <circle>, <ellipse>, and <g> tags.

Instructions:

  1. Create an SVG with viewBox="0 0 200 200".
  2. Draw an outer dark emblem shield using a rounded rectangle (<rect>) with width="180" height="180" x="10" y="10" rx="30".
  3. Place a deep space portal circle at center $(100, 100)$ with radius $65$.
  4. Add a tilted planet inside the portal with center $(100, 100)$, radius $25$, and an orbital ellipse ring with rx="55" and ry="14".
  5. Group the planet and its orbital ring inside a <g transform="rotate(-25 100 100)"> to create an authentic 25-degree orbital tilt!

🏁 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. Confusing Circle cx/cy with Rectangle x/y: Placing a <circle x="100" y="100" r="50"> will cause the circle to render at $(0, 0)$ because circles do not have x/y attributes—they require cx and cy!
  2. Negative Dimensions in SVGs: Setting width="-10", height="-5", or r="-20" is invalid in SVG geometry. Browsers immediately disable rendering of the invalid shape.
  3. The Default Black Fill Gotcha: In SVG, the initial default value for the fill property is #000000 (pure black), and the default stroke is none. If you create a <circle cx="50" cy="50" r="40"/> without styling, it will render as a solid black disc.

💡 Pro Tips

  1. Self-Balancing Rounded Corners: If you set rx="10" on a rectangle, you do NOT need to specify ry="10". The browser automatically mirrors ry = rx by default.
  2. The 1-Line Stadium Pill Formula: To make any rectangle automatically adapt to a pill shape regardless of dynamic width/height, set rx="50%". The SVG 2 engine will clamp the radius to exactly half the shortest dimension.

📌 Key Takeaways

  • <rect> Origins: Anchored from top-left $(x, y)$, dimensioned via width and height, and rounded with rx and ry.
  • <circle> Origins: Anchored from mathematical center $(cx, cy)$ with radial distance r.
  • <ellipse> Origins: Anchored from $(cx, cy)$ with independent semi-major and semi-minor radii rx and ry.
  • <g> Containers: Group shapes together to share cascading styles and apply unified spatial transforms (translate, rotate, scale).
  • Defaults: SVG elements default to a solid black fill (fill="#000000") unless explicitly styled.
  • --
⭐ LEARN: HTML 🌟 ⚔️ QUIZ BATTLE ARENA // ACTIVE
3x
STREAK!
BONUS ACTIVE
COMBO
? Question 1 / 3

How do the positioning origins of <rect> and <circle> differ in the SVG coordinate plane?

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

What happens when you declare <rect width="100" height="40" rx="30" /> in an SVG document?

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

Which SVG element is used to group multiple geometric primitives together and apply a shared rotation transformation?

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