SVG Fundamentals and Practical Usage - From Vector Basics to Animation
What Is SVG - Fundamental Differences from Raster Images
SVG (Scalable Vector Graphics) is an XML-based vector image format. While raster images like JPEG and PNG represent images as pixel collections, SVG defines images through mathematical shape descriptions (points, lines, curves, polygons). This fundamental difference gives SVG the characteristic of never losing quality regardless of magnification.
SVG vs raster comparison:
- Resolution independent: SVG displays crisply on Retina and 4K monitors as vector data. Raster images show pixels when enlarged; SVG has no such problem
- File size: For simple shapes (icons, logos, diagrams), SVG is dramatically smaller. For complex photographic images, raster formats are more efficient
- Editability: SVG is XML editable in text editors. Styles changeable via CSS, dynamically manipulable via JavaScript. Raster pixel data lacks this flexibility
- Accessibility: SVG text is readable by search engines and screen readers.
<title>and<desc>elements add descriptions for accessible images
SVG suits: icons, logos, diagrams, graphs, maps, UI elements, illustrations, animations. SVG doesn't suit: photographs, complex textures, gradient-heavy natural images. Choosing appropriately between SVG and raster by use case is essential.
SVG Basic Structure - Coordinate System and Key Elements
SVG files use XML format with shape elements placed within an <svg> root element. Understanding the coordinate system is fundamental to working with SVG.
The viewBox attribute defines SVG's internal coordinate system. viewBox="0 0 100 100" means coordinate space from (0,0) top-left to (100,100) bottom-right. width and height set actual display size. When viewBox differs from display size, SVG auto-scales.
Key shape elements:
- <rect>: Rectangle with optional rounded corners via
rx - <circle>: Circle with center point and radius
- <ellipse>: Ellipse with separate x and y radii
- <line>: Straight line between two points
- <polyline>: Connected line segments
- <polygon>: Closed polygon shape
- <path>: Most powerful element capable of any shape
- <text>: Text with positioning and alignment
Group with <g> for collective transforms. Place reusable definitions in <defs> and reference with <use> for efficient patterns.
Writing SVG Paths - The d Attribute Command System
The <path> element's d attribute is SVG's most powerful and complex feature. A series of commands draws arbitrary shapes - icon fonts and illustrations are primarily composed of paths.
Key path commands:
- M (moveto): Move pen position
- L (lineto): Draw straight line to point
- H (horizontal): Horizontal line to x coordinate
- V (vertical): Vertical line to y coordinate
- C (curveto): Cubic bezier with two control points and endpoint
- S (smooth curveto): Smooth cubic bezier reflecting previous control point
- Q (quadratic): Quadratic bezier with one control point
- A (arc): Elliptical arc with radius, rotation, and flags
- Z (closepath): Close path back to start
Uppercase commands use absolute coordinates; lowercase use relative (offset from current position). Complex paths are rarely hand-written - typically created in Figma, Illustrator, or Inkscape then exported as SVG. Post-export SVGO optimization removes unnecessary metadata and redundant descriptions, reducing file size.
CSS and JavaScript SVG Manipulation - Dynamic Styling and Interaction
Embedding SVG inline in HTML enables free manipulation of each SVG element via CSS and JavaScript. This enables hover effects, theme switching, data-driven dynamic drawing, and interactive graphics.
SVG-specific CSS properties: fill (fill color, use currentColor to inherit parent's color), stroke (line color), stroke-width (line thickness), stroke-dasharray (dash pattern for drawing effects), stroke-dashoffset (dash start position for path drawing animation), opacity, and transform.
JavaScript manipulation uses the same DOM APIs as HTML (querySelector, setAttribute, addEventListener), making learning cost low for web developers. Data visualization libraries like D3.js and Chart.js dynamically generate SVG for charts and graphs.
CSS transitions on SVG properties enable smooth hover effects: changing fill color, stroke width, or transform on hover with transition timing creates polished interactive icons and UI elements without JavaScript.
SVG Animation - SMIL vs CSS Animation Selection
SVG animation has three methods: SMIL (SVG-native animation), CSS animation, and JavaScript (Web Animations API / GSAP). Each has strengths for different use cases.
CSS animation (recommended): Most common and familiar to web developers. Uses @keyframes and animation properties. GPU-accelerated transform and opacity achieve smooth 60fps animation.
SMIL animation: Written directly in SVG using <animate>, <animateTransform>, <animateMotion> elements. Enables path-following motion difficult with CSS alone. However, Chrome previously considered deprecating SMIL, so CSS/JavaScript is preferred for new implementations.
JavaScript animation (GSAP / Web Animations API): Optimal for complex timeline control, scroll-linked effects, and user-interaction-responsive animation. GSAP is the de facto standard for SVG animation, enabling morphing, path drawing, and stagger animations.
Performance note: For many animated elements (100+), Canvas outperforms SVG. SVG's DOM-based nature means rendering cost increases proportionally with element count.
SVG Optimization and Performance - Practical Considerations
SVG files being text-based often contain unnecessary metadata and redundant descriptions. Optimization can reduce file sizes by 30-70%. For sites using many SVGs (icon sets), optimization effects accumulate for significant performance improvement.
SVGO optimization:
- Remove unnecessary metadata: Editor-inserted comments, namespace declarations, hidden layers
- Round coordinates: Reduce precision from
M 10.123456toM 10.12controlled byfloatPrecision - Optimize paths: Merge redundant commands, convert to relative coordinates, remove whitespace
- Shorten attributes:
fill="#ffffff"tofill="#fff"
Inline SVG vs external file decision:
- Inline: When CSS/JS manipulation needed, reducing HTTP requests, small icons (under 1KB)
- External file: When leveraging browser cache, reusing across pages, no CSS/JS manipulation needed
- SVG sprites: Multiple icons in one file referenced via
<use href="#icon-name">. Reduces requests while enabling caching
Performance note: Complex filters (<feGaussianBlur>, <feDropShadow>) have high rendering cost. On mobile devices, filtered SVGs can cause scroll jank. Use sparingly.