Lesson 55 +10 XP

HTML SVG

HTML SVG

SVG stands for Scalable Vector Graphics. It draws pictures using math, so they stay sharp at any size!

What's so great about SVG?

  • Crisp forever: zoom in and it never gets blurry (it's math, not pixels!).
  • Small files: simple shapes take very little space.
  • Editable with code: you can draw with text!
  • Style with CSS: color it like any element.

The <svg> element

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" fill="red" />
</svg>
  • width and height: the drawing area size.
  • cx, cy: the circle's center.
  • r: the radius (how big the circle is).
  • fill: the inside color.

Basic shapes

Rectangle:

<svg width="400" height="120">
  <rect x="10" y="10" width="100" height="80" fill="blue" stroke="black" stroke-width="3" />
</svg>
  • x, y: where the corner is.
  • stroke: the border color.
  • stroke-width: border thickness.

Circle:

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>

Ellipse (oval):

<svg width="200" height="100">
  <ellipse cx="100" cy="50" rx="90" ry="40" fill="purple" />
</svg>

Line:

<svg width="200" height="100">
  <line x1="0" y1="0" x2="200" y2="100" stroke="red" stroke-width="4" />
</svg>

Polyline (a path of connected lines):

<svg width="200" height="100">
  <polyline points="0,50 50,0 100,50 150,0 200,50" stroke="blue" stroke-width="3" fill="none" />
</svg>

Polygon (a closed shape):

<svg width="200" height="200">
  <polygon points="100,10 190,160 10,160" fill="gold" stroke="brown" stroke-width="3" />
</svg>

SVG vs Canvas

  • SVG: vector, stays sharp, great for logos and simple shapes, easy to animate each part.
  • Canvas: pixel-based drawing (mostly via JavaScript), great for games and complex graphics.

TL;DR

  • SVG draws shapes with math: crisp at any size.
  • <circle>, <rect>, <ellipse>, <line>, <polyline>, <polygon>.
  • fill = inside color, stroke = border color.
  • <svg width height> is the drawing board.
  • SVG for logos/shapes, Canvas for games.