Skip to content

HTML5 SVG

SVG (Scalable Vector Graphics) is an XML-based markup language for describing two-dimensional vector graphics. It's an open standard from the W3C.

Unlike Canvas, SVG is not pixel-based but defines shapes through mathematical equations. This means you can infinitely enlarge SVG images without any quality loss, making them ideal for logos, icons, and illustrations requiring high fidelity.

Using SVG in HTML

You can embed <svg> tags directly into HTML documents to create graphics.

html
<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
  • The <svg> element is the container for all SVG graphics. The width and height attributes define the SVG image dimensions.
  • <circle> is one of the predefined SVG shapes, used to create a circle.
    • cx, cy define the center coordinates.
    • r defines the radius.
    • stroke and stroke-width define the outline color and width.
    • fill defines the shape's fill color.

Advantages of SVG

  • Scalability: Scales infinitely without distortion, looking crisp at any resolution.
  • Accessibility: SVG is pure text XML, can be indexed by search engines, and accessed by screen readers. You can add titles and descriptions to SVG elements.
  • Manipulability: Each SVG shape is a DOM element that can be styled with CSS and have interactions added with JavaScript (like event listeners), just like regular HTML elements.
  • Small file size: For simple graphics, SVG files are usually smaller than bitmaps (like PNG, JPG).

Common SVG Shapes

SVG provides a series of predefined shape tags, making it very simple to create common graphics.

  • <rect>: Rectangle

    html
    <rect width="200" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
  • <line>: Line

    html
    <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" />
  • <ellipse>: Ellipse

  • <polygon>: Polygon (made up of multiple connected straight lines)

  • <path>: Path. This is the most powerful SVG element, capable of creating any complex shape, including curves.

SVG vs. Canvas

Choosing SVG or Canvas depends on your specific needs:

FeatureSVGCanvas
TypeVector graphics (shape-based)Bitmap graphics (pixel-based)
DOMEach shape is a DOM nodeSingle HTML element, no internal DOM
ScalingLossless scalingGets distorted when enlarged
InteractionCan be manipulated directly via CSS and JSRequires JS events and coordinate calculations
Use CasesIcons, logos, charts, mapsGames, image processing, complex scene rendering

Rule of thumb: If you need static, interactive, high-fidelity graphics, prefer SVG. If you need to process many pixels, do real-time rendering, or develop games, Canvas is a better choice.

Content is for learning and research only.