HTML SVG

SVG stands for Scalable Vector Graphics. Unlike <canvas>, SVG shapes are described declaratively as XML markup directly in the page — you write tags like <circle> or <rect> instead of calling JavaScript drawing functions.

1) Embedding SVG in HTML


<svg width="200" height="100">
  <circle cx="50" cy="50" r="40" fill="green" />
</svg>

SVG can be placed directly inside your HTML, exactly like any other element.

2) Circle and Rectangle


<svg width="220" height="120">
  <circle cx="60" cy="60" r="40" fill="#3498db" />
  <rect x="120" y="20" width="80" height="60" fill="#e67e22" />
</svg>

<circle> uses center (cx, cy) and radius (r). <rect> uses top-left (x, y) plus width/height.

3) Line, Polygon, and Text


<svg width="220" height="120">
  <line x1="10" y1="10" x2="200" y2="100" stroke="black" stroke-width="2" />
  <polygon points="60,10 100,90 20,90" fill="#9b59b6" />
  <text x="120" y="50" fill="#222">Hello SVG</text>
</svg>

<line> needs two endpoints. <polygon> takes a list of x,y points to make any closed shape (triangle here). <text> draws text at a given position.

4) viewBox and Scalability


<svg viewBox="0 0 100 100" width="100%">
  <circle cx="50" cy="50" r="45" fill="#2ecc71" />
</svg>

viewBox defines an internal coordinate system that scales to fit the element's rendered size — this is why SVG stays crisp at any zoom level, unlike a bitmap.

5) SVG vs Canvas

  • Resolution: SVG is vector-based and resolution-independent (crisp at any zoom); Canvas is a pixel-based bitmap.
  • Access: SVG shapes are real DOM nodes — you can select and style them with CSS/JS; Canvas content is just pixels with no per-shape DOM access.
  • Best for: SVG suits icons, logos, charts, and illustrations; Canvas suits games, image editing, and per-pixel effects.
  • Performance: SVG can slow down with thousands of elements; Canvas handles very large numbers of drawn objects better since it's just pixels.
  • Editing: To change an SVG shape you update its attributes; to change a Canvas drawing you must redraw the whole scene.

Live Demo

This SVG is rendered directly by the browser as markup — no JavaScript required:

Live SVG

Best Practices:

  • Use viewBox with a percentage width to make SVG graphics responsive.
  • Prefer SVG for logos, icons, and diagrams that must stay sharp on any screen (including retina displays).
  • SVG elements can be styled with CSS classes and animated with CSS/JS, just like regular HTML.
  • Choose Canvas instead when you need to draw thousands of shapes or do pixel-level manipulation (e.g. games).