What are Canvas and SVG?
Both draw graphics, but work differently.
Canvas: (Pixel-based drawing)
What is Canvas? A blank drawing surface that you control with JavaScript. Like Microsoft Paint.
1<canvas id="myCanvas" width="400" height="200" style="border:1px solid black;"></canvas>
2
3<script>
4 // Get the canvas and drawing tools
5 const canvas = document.getElementById('myCanvas');
6 const ctx = canvas.getContext('2d');
7
8 // Draw a red rectangle (x, y, width, height)
9 ctx.fillStyle = 'red';
10 ctx.fillRect(20, 20, 100, 60);
11
12 // Draw a blue circle (x, y, radius, startAngle, endAngle)
13 ctx.fillStyle = 'blue';
14 ctx.beginPath();
15 ctx.arc(250, 80, 40, 0, 2 * Math.PI);
16 ctx.fill();
17
18 // Draw a line
19 ctx.beginPath();
20 ctx.moveTo(20, 150);
21 ctx.lineTo(380, 150);
22 ctx.strokeStyle = 'green';
23 ctx.stroke();
24
25 // Draw text
26 ctx.fillStyle = 'black';
27 ctx.font = '20px Arial';
28 ctx.fillText('Hello Canvas', 120, 180);
29</script>Canvas best for: Games, real-time graphics, image editing, charts with many data points.
SVG: (Vector graphics)
What is SVG? Shapes defined in XML that scale perfectly without losing quality.
1<svg width="300" height="200" viewBox="0 0 300 200">
2 <!-- Circle (cx, cy, r) -->
3 <circle cx="60" cy="80" r="40" fill="red" stroke="black" stroke-width="3"/>
4
5 <!-- Rectangle (x, y, width, height) -->
6 <rect x="120" y="40" width="100" height="80" fill="blue" rx="10" ry="10"/>
7
8 <!-- Line (x1, y1, x2, y2) -->
9 <line x1="20" y1="170" x2="280" y2="170" stroke="green" stroke-width="4"/>
10
11 <!-- Text (x, y) -->
12 <text x="30" y="190" fill="black" font-size="16">SVG Graphics</text>
13</svg>SVG best for: Logos, icons, illustrations, charts (where you want perfect scaling).
Canvas vs SVG comparison:
Feature | Canvas | SVG |
|---|---|---|
Type | Pixel-based | Vector-based |
Scaling | Loses quality | Perfect quality (infinite zoom) |
Performance | Good for many objects | Good for few objects |
JavaScript | Required for drawing | Can be drawn without JS |
Best for | Games, real-time graphics | Logos, icons, illustrations |
