Canvas and SVG
HTML5 has two ways to draw graphics: Canvas (bitmap, drawn with JavaScript) and SVG (vector, written as HTML-like markup). Both are powerful and serve different use cases.
SVG — Scalable Vector Graphics
Example 1 — SVG Shapes
<!-- SVG is written directly in HTML --> <svg width="300" height="150" viewBox="0 0 300 150"> <!-- Rectangle --> <rect x="10" y="10" width="80" height="60" fill="#e8401c" rx="8"/> <!-- Circle --> <circle cx="150" cy="50" r="40" fill="#3b82f6"/> <!-- Line --> <line x1="220" y1="10" x2="280" y2="90" stroke="#22c55e" stroke-width="3"/> <!-- Text --> <text x="10" y="130" fill="#fff" font-size="14"> SVG Graphics </text> </svg>
SVG is XML-based markup. It scales perfectly at any size. Style with CSS or attributes. Great for logos, icons, and charts.
Canvas — JavaScript Drawing
Example 2 — Canvas with JavaScript
<canvas id="myCanvas" width="300" height="150"> Canvas not supported in your browser. </canvas> <script> var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d'); // Draw filled rectangle ctx.fillStyle = '#e8401c'; ctx.fillRect(10, 10, 80, 60); // Draw circle ctx.fillStyle = '#3b82f6'; ctx.beginPath(); ctx.arc(150, 75, 40, 0, Math.PI * 2); ctx.fill(); // Draw text ctx.fillStyle = '#22c55e'; ctx.font = '16px Arial'; ctx.fillText('Canvas!', 220, 75); </script>
Canvas is a bitmap — drawn with JavaScript. Good for games, animations, image processing. SVG is declarative markup — better for static or interactive graphics.
SVG vs Canvas
SVGVector. Scales perfectly. DOM elements (styled with CSS). Better for logos, icons, charts.
CanvasBitmap. JavaScript API. Better for games, animations, pixel manipulation, real-time graphics.
SVG accessibilityAdd title and desc inside SVG for screen readers. Supports tabindex and focus events.
Canvas accessibilityNo built-in accessibility. Provide fallback text inside the canvas tags for screen readers.