Tutorials HTML SVG Basics
Ch 20 / 40
Chapter 20 Intermediate 10 min read HTML

HTML SVG Basics

SVG (Scalable Vector Graphics) is an XML-based language for describing two-dimensional vector graphics directly in HTML. Unlike Canvas (pixel-based, imperative), SVG graphics are part of the DOM — fully styleable with CSS, animatable, accessible to screen readers, and infinitely scalable without pixelation. In this chapter you'll master all core SVG elements, the path mini-language, gradients, transforms, CSS animations, and when to choose SVG over Canvas.

What you'll learn
What SVG is and how to embed it inline in HTML
Shape elements — <rect>, <circle>, <ellipse>, <line>, <polygon>
The <path> element and its d-attribute command language
Text, gradients (linearGradient, radialGradient), and <defs>
Transforms — translate, rotate, scale — and the <g> group element
CSS animations on SVG elements and SVG vs Canvas decision guide

What is SVG and How to Embed It

SVG is written in XML markup — tags, attributes, and nesting — embedded directly in HTML using the <svg> element. Every SVG element becomes a real DOM node that you can select with CSS selectors, manipulate with JavaScript, and animate with CSS transitions or @keyframes.

viewBox — the coordinate space
The viewBox attribute defines the internal coordinate system: viewBox="minX minY width height". The SVG is drawn in this space, then scaled to fit the element's display size. This makes SVG resolution-independent — a viewBox of 0 0 100 100 renders crisply at any display size from 50px to 5000px.
fill and stroke — painting model
SVG shapes are painted with fill (interior colour) and stroke (outline). Both accept any CSS colour value. You can set them as XML attributes directly on the element, or via CSS — CSS always wins over element attributes.
Three ways to use SVG
Inline SVG (inside HTML) — full CSS + JS access, best for interactive and animated graphics. External file (<img src="icon.svg">) — simple, cacheable, no DOM access. CSS background (background: url(icon.svg)) — for decorative images only.
HTML — SVG element anatomy
<!-- Inline SVG — part of the HTML DOM -->
<svg
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 200 100"
  width="400"
  height="200"
  role="img"
  aria-label="K2infocom logo"
>
  <!-- shapes go here -->
  <rect x="10" y="10" width="80" height="60"
        fill="#e44d26" rx="8"/>
</svg>

<!-- External SVG as image (no DOM access) -->
<img src="logo.svg" alt="K2infocom logo" width="200">

SVG Shape Elements — Reference Cards

SVG provides eight dedicated shape elements. Each has its own set of attributes — there are no methods like Canvas. Everything is declarative XML:

Live SVG — All basic shapes rendered inline in the page
rect circle ellipse line polyline polygon
<rect> Rectangle
Draws a rectangle. rx and ry round the corners — set only rx for uniform border-radius.
x, y, width, height
rx, ry (corner radius)
<circle> Circle
Draws a perfect circle. Centre position with cx/cy, size with r (radius).
cx, cy (centre)
r (radius)
<ellipse> Ellipse
Draws an ellipse with separate horizontal (rx) and vertical (ry) radii.
cx, cy (centre)
rx (x-radius), ry (y-radius)
<line> Line
Draws a straight line between two points. Requires stroke — lines have no fill area to render.
x1, y1 (start)
x2, y2 (end)
stroke-linecap
<polyline> / <polygon> Multi-point shapes
polyline is an open multi-segment line. polygon auto-closes the path — last point connects back to first. Both take a points attribute.
points="x1,y1 x2,y2 x3,y3 ..."
<g> Group
Groups child elements — applies shared transforms, styles, and opacity to all children. Also used to organise related shapes logically. Equivalent to a <div> for SVG elements.
transform, opacity, id, class
Inherits fill/stroke to children
SVG — All basic shape elements
<svg viewBox="0 0 500 200" xmlns="http://www.w3.org/2000/svg">

  <!-- Rounded rectangle -->
  <rect x="10" y="20" width="100" height="80"
        rx="12" fill="#e44d26" stroke="#c0392b" stroke-width="2"/>

  <!-- Circle -->
  <circle cx="180" cy="60" r="50"
           fill="#3b82f6" fill-opacity="0.85"/>

  <!-- Ellipse -->
  <ellipse cx="290" cy="60" rx="70" ry="40"
            fill="none" stroke="#a855f7" stroke-width="3"/>

  <!-- Line -->
  <line x1="380" y1="10" x2="480" y2="110"
        stroke="#22c55e" stroke-width="4" stroke-linecap="round"/>

  <!-- Polygon (triangle — auto-closes) -->
  <polygon points="60,140 10,190 110,190"
            fill="#f59e0b" stroke="#d97706" stroke-width="1.5"/>

  <!-- Polyline (open path) -->
  <polyline points="160,190 180,140 200,170 220,120 240,180"
             fill="none" stroke="#06b6d4" stroke-width="3"
             stroke-linejoin="round"/>

</svg>

The <path> Element — SVG's Most Powerful Shape

The <path> element can draw any shape — including circles, custom curves, icons, and complex illustrations. All the shape instructions are encoded in the d attribute using a compact command language. Uppercase commands use absolute coordinates; lowercase use relative coordinates (offset from the current point).

Command Name Parameters What it does
M / m Move To x y Move the "pen" to (x, y) without drawing. Every path starts with M.
L / l Line To x y Draw a straight line from the current point to (x, y).
H / h Horizontal Line x Draw a horizontal line to absolute x (or relative dx). Shorthand for L x currentY.
V / v Vertical Line y Draw a vertical line to absolute y (or relative dy). Shorthand for L currentX y.
C / c Cubic Bézier x1 y1, x2 y2, x y Draw a cubic Bézier curve. Two control points (x1,y1) and (x2,y2), ending at (x,y).
Q / q Quadratic Bézier x1 y1, x y Draw a quadratic Bézier curve. One control point (x1,y1), ending at (x,y).
A / a Arc rx ry x-rot large-arc sweep x y Draw an elliptical arc between current point and (x,y).
Z / z Close Path — Draw a straight line back to the first point in the current sub-path and close it.
Live SVG — Path element: triangle, curved arrow, heart, and custom wave
M L Z C (cubic) heart path Q (quadratic)
SVG — path element examples
<!-- Triangle: M(start) L(line) L(line) Z(close) -->
<path
  d="M 100 10
     L 10 90
     L 190 90
     Z"
  fill="#a855f7"
  stroke="#7c3aed"
  stroke-width="2"
/>

<!-- S-curve using cubic bezier -->
<!-- C cp1x,cp1y cp2x,cp2y endx,endy -->
<path
  d="M 20 80
     C 20 20, 100 20, 100 80
     C 100 140, 180 140, 180 80"
  fill="none"
  stroke="#e44d26"
  stroke-width="3"
/>

<!-- Simple icon arrow using H (horizontal) and V (vertical) -->
<path
  d="M 10 50
     H 80
     L 60 30
     M 80 50
     L 60 70"
  fill="none"
  stroke="#22c55e"
  stroke-width="3"
  stroke-linecap="round"
  stroke-linejoin="round"
/>
You Rarely Write Paths by Hand
SVG paths for icons and logos are generated by design tools like Figma, Illustrator, or Inkscape — you export as SVG and copy the d attribute. Understanding the commands helps you read, debug, and make minor edits to exported SVG code. Libraries like Heroicons, Lucide, and Phosphor provide ready-made SVG icon paths for web projects.

Text in SVG

The <text> element renders scalable, selectable, accessible text. Use <tspan> for inline formatting of portions of the text. SVG text is real DOM text — searchable and accessible, unlike Canvas text which is rasterised pixels.

SVG — text and tspan elements
<!-- Basic text -->
<text
  x="50%"
  y="50"
  text-anchor="middle"       <!-- start | middle | end -->
  dominant-baseline="middle"  <!-- aligns vertically -->
  font-size="24"
  font-family="Segoe UI, sans-serif"
  font-weight="700"
  fill="#e44d26"
>K2infocom</text>

<!-- tspan: inline formatting within text -->
<text x="20" y="90" font-size="18" fill="#f0f0e8">
  Learn
  <tspan fill="#3b82f6" font-weight="700">HTML</tspan>
  and
  <tspan fill="#a855f7" font-weight="700">SVG</tspan>
</text>

<!-- Text on a path -->
<defs>
  <path id="curve" d="M 20 120 Q 200 40 380 120"/>
</defs>
<text font-size="16" fill="#f59e0b">
  <textPath href="#curve">
    K2infocom — Web Dev with SVG!
  </textPath>
</text>

Gradients and <defs>

SVG gradients are defined inside <defs> — a section for reusable definitions that aren't rendered themselves. Each gradient gets an id, then shapes reference it with fill="url(#gradientId)".

Live SVG — Linear gradient, radial gradient, and stroke gradient
linearGradient radialGradient stroke gradient
SVG — linearGradient, radialGradient, and defs
<svg viewBox="0 0 400 160" xmlns="http://www.w3.org/2000/svg">

  <defs>

    <!-- Linear gradient: left → right -->
    <linearGradient id="btnGrad"
                     x1="0%" y1="0%"
                     x2="100%" y2="0%">
      <stop offset="0%"   stop-color="#e44d26"/>
      <stop offset="100%" stop-color="#f59e0b"/>
    </linearGradient>

    <!-- Radial gradient: inner glow effect -->
    <radialGradient id="glowGrad"
                     cx="40%" cy="35%"
                     r="60%">
      <stop offset="0%"   stop-color="#ffffff" stop-opacity="0.9"/>
      <stop offset="100%" stop-color="#a855f7" stop-opacity="1"/>
    </radialGradient>

  </defs>

  <!-- Use gradients via url(#id) -->
  <rect x="10" y="20" width="160" height="60"
        rx="10" fill="url(#btnGrad)"/>

  <circle cx="300" cy="80" r="70"
           fill="url(#glowGrad)"/>

</svg>

Transforms — translate, rotate, scale

The transform attribute applies geometric transformations to any SVG element or group. Multiple transforms can be combined by listing them space-separated — they are applied right-to-left.

Live SVG — translate, rotate, scale transforms with grouping
translate(40,55) rotate(45) scale(1.8) combined
SVG — transform attribute: translate, rotate, scale
<!-- translate(tx, ty) — move element -->
<rect x="0" y="0" width="60" height="40"
      fill="#e44d26"
      transform="translate(50, 30)"/>

<!-- rotate(angle, cx, cy) — rotate around point -->
<rect x="-30" y="-20" width="60" height="40"
      fill="#3b82f6"
      transform="translate(150,60) rotate(45)"/>

<!-- scale(sx, sy) — scale element -->
<circle cx="0" cy="0" r="20"
         fill="#a855f7"
         transform="translate(250,60) scale(2)"/>

<!-- Group: shared transform on all children -->
<g transform="translate(350,60) rotate(30)"
   fill="#f59e0b" opacity="0.9">
  <circle cx="0" cy="0" r="20"/>
  <rect x="25" y="-10" width="30" height="20"/>
</g>

Animating SVG with CSS

Because inline SVG elements are part of the DOM, you can animate them with CSS transitions and @keyframes — targeting SVG-specific properties like fill, stroke, stroke-dashoffset, r (circle radius), and transform.

Live SVG CSS Animations — spinning, pulsing, drawing stroke, colour cycling, bouncing
spin pulse stroke draw color cycle bounce
HTML + CSS — SVG CSS animation examples
<!-- Spinning shape -->
<rect x="-25" y="-25" width="50" height="50"
      fill="#e44d26"
      transform="translate(50,50)"
      style="transform-origin: 0 0;
             transform-box: fill-box;
             animation: spin 2s linear infinite;"/>

<!-- Stroke draw-on effect (dasharray trick) -->
<path
  d="M 10 50 Q 100 0 190 50"
  fill="none"
  stroke="#3b82f6"
  stroke-width="3"
  stroke-dasharray="200"  <!-- total path length -->
  stroke-dashoffset="200"  <!-- start fully hidden -->
  style="animation: drawStroke 2s ease forwards;"
/>

<style>
  @keyframes spin {
    to { transform: rotate(360deg); }
  }

  @keyframes drawStroke {
    to { stroke-dashoffset: 0; } /* reveal stroke */
  }

  @keyframes pulse {
    0%, 100% { r: 20px; }
    50%       { r: 32px; }
  }

  @keyframes colorCycle {
    0%   { fill: #e44d26; }
    33%  { fill: #a855f7; }
    66%  { fill: #22c55e; }
    100% { fill: #e44d26; }
  }

  /* Hover effects on SVG via CSS */
  circle:hover { opacity: 0.7; cursor: pointer; }
  rect { transition: fill 0.3s; }
  rect:hover { fill: #f06529; }
</style>
The Stroke Dasharray Draw Trick
Set stroke-dasharray to the total path length and stroke-dashoffset to the same value (fully hidden). Then animate stroke-dashoffset to 0 — the stroke appears to draw itself. Get exact path length with path.getTotalLength() in JavaScript.

SVG vs Canvas — When to Use Which

Both SVG and Canvas render graphics in the browser, but they work very differently. Choosing the right one depends on your use case:

SVG — Use When…
You need resolution independence — icons, logos, and illustrations that must be crisp at any size
Shapes need to be accessible — screen readers can read text and title elements inside SVG
You need CSS hover/focus effects and JavaScript event listeners on individual shapes
Static or lightly animated graphics — charts, infographics, loading spinners, progress rings
Not ideal for thousands of elements — SVG DOM gets heavy; performance degrades past ~1000 nodes
Canvas — Use When…
You need high-performance rendering of thousands of objects — particle systems, games, real-time data
Pixel-level manipulation — image filters, photo editors, webcam effects, custom video processing
Frame-by-frame animation at 60fps — browser games, physics simulations, generative art
Not ideal for resolution-sensitive output — rasterised pixels become blurry when zoomed
No built-in accessibility — text and shapes are not in the DOM, requiring manual ARIA workarounds

Common Mistakes — Do's & Don'ts

These are the most frequent SVG mistakes beginners make:

Do — Correct
<!-- viewBox for resolution independence -->
<svg viewBox="0 0 100 100"
     width="200" height="200">
  <!-- crisp at any size -->
</svg>

<!-- Accessible inline SVG -->
<svg role="img"
     aria-label="K2infocom logo">
  <title>K2infocom logo</title>
  ...
</svg>

<!-- defs for reuse -->
<defs>
  <linearGradient id="grad">...</linearGradient>
</defs>
Don't — Wrong
<!-- No viewBox — fixed pixel size only -->
<svg width="200" height="200">
  <!-- blurry at different display sizes -->
</svg>

<!-- No accessibility on icon SVG -->
<svg>
  <!-- screen readers say "svg" with no context -->
  <path d="M 10 10 ..."/>
</svg>

<!-- Duplicating gradient definitions -->
<rect fill="url(#grad)"/>
<circle fill="url(#grad2)"/>
<!-- Should use one gradient in <defs> -->

Try It Yourself

Edit the SVG demo below and click Open in Editor to see shapes, gradients, transforms, and CSS animations all running live in full screen.

Live Editor
✎ Editor
👁 Preview
Try This
Click the orange rectangle in the Shapes section — the onclick attribute fires a JavaScript alert directly on the SVG element. Try changing the gradient colours in <stop stop-color>. Modify the star path's d attribute and watch the shape update instantly.
Free Resource
HTML5 Cheat Sheet — All Tags & Attributes
One printable PDF covering all SVG shape elements, path commands, gradient API, transform syntax, CSS animation properties, and SVG vs Canvas comparison.
Download PDF
Featured Course — Enroll Now
Modern Web Development With AI
Master HTML, CSS, JavaScript, React, and Node.js in one industry-ready curriculum with real projects and placement support.
120+
Chapters
40 hrs
Content
10
Projects
4.9 ⭐
Rating
HTML5 CSS3 JavaScript React.js Node.js MongoDB AI Tools

Quick Check — Chapter 20

Expand each question to check your understanding before moving on to the multiple choice quiz.

Questions & Answers
The viewBox attribute defines the internal coordinate space of an SVG — the virtual canvas that your shapes are drawn on. It takes four values: minX minY width height. The SVG viewport (the element's actual display size set by width/height or CSS) is then stretched or shrunk to fit this coordinate space — automatically scaling all shapes proportionally. This makes SVG resolution-independent: you draw a shape at viewBox="0 0 100 100" and it renders crisp at 50px, 500px, or 5000px display size. Without viewBox, the SVG has no coordinate reference — shapes may overflow or not scale as expected.
Both elements take a points attribute — a list of x,y coordinate pairs separated by spaces. The difference is how the shape is closed. <polyline> draws connected line segments but leaves the path open — the last point is not connected back to the first. <polygon> automatically closes the path by drawing a straight line from the last point back to the first point. This means <polygon> always creates a closed, fillable shape, while <polyline> is an open line path — it can have a stroke but its fill is unreliable (it fills the gap between start and end, which is usually not what you want).
This is a technique to make a path appear to draw itself progressively. It works by exploiting how dashed strokes work. stroke-dasharray defines the dash pattern — setting it to the total length of the path creates one single dash exactly as long as the entire path. stroke-dashoffset shifts where the dash starts — setting it to the same total length hides the entire stroke (the dash is shifted completely off the visible area). Animating stroke-dashoffset from the total length down to 0 with CSS @keyframes gradually reveals the stroke — creating the "drawing on" effect. Get the total length in JavaScript with pathElement.getTotalLength().
When SVG is loaded as an <img>, the browser treats it as an external resource — it is isolated from the page's DOM. You cannot apply CSS classes to internal shapes, cannot run JavaScript that interacts with the SVG elements, cannot change fill colour with CSS variables, and cannot add hover/click event listeners to individual shapes. Inline SVG, on the other hand, makes every <circle>, <rect>, and <path> a real DOM node — selectable with querySelector, styleable with CSS, animatable with CSS transitions and @keyframes, and interactive with JavaScript event listeners. Use <img> for simple decorative icons you don't need to interact with; use inline SVG for interactive, animated, or CSS-themed graphics.
<defs> is a container for reusable definitions that are not rendered directly — they only render when referenced by other elements. It is equivalent to defining CSS variables or a template. Common contents: <linearGradient> and <radialGradient> (referenced with fill="url(#id)"), <pattern> (repeating tile fill), <clipPath> (masking shapes), <filter> (blur, shadow effects), <symbol> (reusable icon templates referenced with <use>), and <path> definitions for <textPath>. Always put gradients and patterns in <defs> rather than duplicating them on each element.
Choose SVG when: you need infinitely scalable graphics (icons, logos, illustrations); shapes need CSS hover/click interactions; accessibility matters (SVG text is selectable and screen-reader readable); you're building charts, infographics, or UI graphics; the number of elements is moderate (under ~1000). Choose Canvas when: you need pixel-level manipulation (image filters, photo editors); performance is critical with thousands of moving objects (particle systems, game engines); you're doing frame-by-frame animation at 60fps; you need to process video frames or apply effects in real time. The rule of thumb: SVG for graphics that are part of the document; Canvas for dynamic pixel rendering that replaces a display.
Multiple Choice Questions
MCQ 1 of 4
Which SVG element automatically closes the path by connecting the last point back to the first?
MCQ 2 of 4
How do you reference a gradient defined in <defs id="myGrad"> on a shape's fill?
MCQ 3 of 4
In the SVG <path> d attribute, what does the Z command do?
MCQ 4 of 4
Which is the best choice for a browser game with 5,000 moving particles?
Chapter Summary
  • SVG is XML-based vector graphics embedded inline in HTML. Every element is a DOM node — styleable with CSS, interactive with JS, accessible to screen readers, and infinitely scalable. The viewBox attribute defines the coordinate space for resolution independence.
  • Shape elements: <rect> (x, y, width, height, rx), <circle> (cx, cy, r), <ellipse> (cx, cy, rx, ry), <line> (x1, y1, x2, y2), <polyline> (open), <polygon> (auto-closes). Painted with fill and stroke.
  • The <path> element draws any shape using the d attribute: M (move), L (line), H/V (horizontal/vertical), C (cubic Bézier), Q (quadratic Bézier), A (arc), Z (close).
  • Gradients go in <defs> and are referenced with fill="url(#id)". <linearGradient> and <radialGradient> use <stop offset color> children.
  • Transforms: translate(tx, ty), rotate(angle), scale(sx, sy) — applied via the transform attribute. Use <g> to group elements and apply shared transforms.
  • CSS animations work on SVG — animate fill, stroke, transform, stroke-dashoffset, and r. Choose SVG for icons, charts, and accessible UI graphics; Canvas for games, particle systems, and pixel manipulation.
~10 min read
Intermediate level
Chapter 20 of 40

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
If this tutorial helped you, a 5-star Google review means a lot. It helps other learners discover our free content and motivates us to keep improving.
500+ Reviews (Target)
Write a Google Review
Join WhatsApp Channel