SVG Graphics in HTML

Introduction to SVG

SVG (Scalable Vector Graphics) is an XML-based vector image format for two-dimensional graphics. Unlike raster formats (JPEG, PNG, GIF), SVG images remain crisp and clear at any resolution or size.

Key Features of SVG:

  • Vector-based (resolution independent)
  • XML-based (human-readable)
  • Supports animation and interactivity
  • Searchable and accessible
  • Scriptable with JavaScript
  • Stylable with CSS

SVG vs. Canvas:

  • SVG is vector-based; Canvas is pixel-based
  • SVG has better accessibility
  • Canvas has better performance for complex animations
  • SVG elements are part of the DOM; Canvas is a single element
  • SVG is declarative; Canvas is imperative

Adding SVG to HTML

There are several ways to include SVG in your HTML documents:

1. Inline SVG

SVG code is directly embedded in the HTML document:

<!DOCTYPE html> <html> <body> <h1>Inline SVG Example</h1> <svg width="100" height="100"> <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" /> </svg> </body> </html>

2. Using <img> Tag

Reference an external SVG file like any other image:

<img src="image.svg" alt="SVG Image" width="100" height="100">

3. Using CSS Background

Use SVG as a CSS background image:

.logo { width: 100px; height: 100px; background-image: url('logo.svg'); background-size: contain; }

4. Using <object> Tag

Embed an external SVG file that can be manipulated with JavaScript:

<object data="image.svg" type="image/svg+xml" width="100" height="100"></object>

5. Using <iframe> Tag

Embed an SVG document in an iframe:

<iframe src="image.svg" width="100" height="100" frameborder="0"></iframe>
Note: Inline SVG provides the most flexibility for manipulation with CSS and JavaScript, but external SVG files can be cached by the browser for better performance.

Basic SVG Elements

The <svg> Element

The <svg> element is the container for SVG graphics:

<svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <!-- SVG content goes here --> </svg>

Key attributes:

  • width and height: Dimensions of the SVG viewport
  • viewBox: Defines the coordinate system (minX, minY, width, height)
  • xmlns: XML namespace for SVG

Basic Shapes

Rectangle

<rect x="10" y="10" width="80" height="60" fill="blue" />

Circle

<circle cx="50" cy="40" r="30" fill="red" />

Ellipse

<ellipse cx="50" cy="40" rx="40" ry="20" fill="green" />

Line

<line x1="10" y1="10" x2="90" y2="70" stroke="purple" stroke-width="2" />

Polyline

<polyline points="10,10 30,30 10,50 70,50" fill="none" stroke="orange" stroke-width="2" />

Polygon

<polygon points="50,10 90,40 70,80 30,80 10,40" fill="teal" />

Path

<path d="M10,30 Q50,5 90,30 T170,30" fill="none" stroke="brown" stroke-width="2" />

Text

<text x="10" y="40" fill="navy" font-size="16">SVG Text</text>
SVG Text

Styling SVG with CSS

SVG elements can be styled with CSS, similar to HTML elements:

<svg width="200" height="100"> <style> .circle { fill: gold; stroke: maroon; stroke-width: 3px; } .circle:hover { fill: orange; stroke-width: 5px; } </style> <circle class="circle" cx="50" cy="50" r="40" /> </svg>

Common SVG CSS properties:

  • fill: Fill color (equivalent to background-color)
  • stroke: Outline color (equivalent to border-color)
  • stroke-width: Outline width
  • stroke-dasharray: Creates dashed lines
  • opacity: Overall transparency
  • fill-opacity: Fill transparency
  • stroke-opacity: Stroke transparency

SVG Path Element

The <path> element is the most powerful SVG element, allowing you to create any shape using a series of commands:

<path d="M10,30 L90,30 L50,90 Z" fill="purple" />

Path Commands

Command Description Example
M / m Move to (absolute/relative) M10,10 - Move to point (10,10)
L / l Line to (absolute/relative) L50,50 - Draw line to point (50,50)
H / h Horizontal line (absolute/relative) H80 - Draw horizontal line to x=80
V / v Vertical line (absolute/relative) V120 - Draw vertical line to y=120
C / c Cubic Bézier curve (absolute/relative) C10,30 30,30 50,10
Q / q Quadratic Bézier curve (absolute/relative) Q25,25 50,10
A / a Elliptical arc (absolute/relative) A25,25 0 0,1 50,50
Z / z Close path Z - Close the current path

SVG Gradients and Patterns

Linear Gradient

<svg width="200" height="100"> <defs> <linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="0%"> <stop offset="0%" style="stop-color:rgb(255,0,0)" /> <stop offset="100%" style="stop-color:rgb(0,0,255)" /> </linearGradient> </defs> <rect width="200" height="100" fill="url(#gradient1)" /> </svg>

Radial Gradient

<svg width="200" height="100"> <defs> <radialGradient id="gradient2" cx="50%" cy="50%" r="50%" fx="50%" fy="50%"> <stop offset="0%" style="stop-color:rgb(255,255,255)" /> <stop offset="100%" style="stop-color:rgb(0,128,0)" /> </radialGradient> </defs> <rect width="200" height="100" fill="url(#gradient2)" /> </svg>

Pattern

<svg width="200" height="100"> <defs> <pattern id="pattern1" patternUnits="userSpaceOnUse" width="20" height="20"> <circle cx="10" cy="10" r="5" fill="blue" /> </pattern> </defs> <rect width="200" height="100" fill="url(#pattern1)" /> </svg>

SVG Animation

SVG elements can be animated in several ways:

1. Using CSS Animations

<style> .pulse { animation: pulse 2s infinite; } @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.2); } 100% { transform: scale(1); } } </style> <svg width="100" height="100"> <circle class="pulse" cx="50" cy="50" r="30" fill="red" /> </svg>

2. Using SMIL Animation

SVG has its own animation system called SMIL (Synchronized Multimedia Integration Language):

<svg width="100" height="100"> <circle cx="50" cy="50" r="30" fill="blue"> <animate attributeName="r" values="30;40;30" dur="2s" repeatCount="indefinite" /> </circle> </svg>

3. Using JavaScript

JavaScript can be used to animate SVG elements programmatically:

<svg id="js-animation" width="100" height="100"> <rect id="moving-rect" x="10" y="40" width="20" height="20" fill="green" /> </svg> <script> const rect = document.getElementById('moving-rect'); let x = 10; const animate = () => { x = (x + 1) % 80; rect.setAttribute('x', x + 10); requestAnimationFrame(animate); }; animate(); </script>

Best Practices for SVG in HTML

  • Use SVG for logos, icons, and illustrations that need to be sharp at any size
  • Optimize SVG files to reduce file size (remove unnecessary metadata)
  • Use inline SVG when you need to manipulate elements with CSS or JavaScript
  • Include the viewBox attribute for proper scaling
  • Add role="img" and aria-label attributes for accessibility
  • Use meaningful id and class names for SVG elements
  • Consider using SVG sprites for multiple icons
  • Test SVG rendering across different browsers
  • Provide fallback for older browsers that don't support SVG