Canvas and SVG Graphics
HTML5 supports two major graphics approaches: canvas and SVG. They solve different problems.
<canvas>
Purpose:
- creates a drawing surface controlled with JavaScript
Important attributes:
widthheight
Example:
<canvas id="chart" width="400" height="200"></canvas>
Use canvas for:
- simple games
- drawing tools
- particle effects
- charts drawn with JavaScript
Simple Canvas Example
<canvas id="demo" width="300" height="150"></canvas>
<script>
const canvas = document.getElementById("demo");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "royalblue";
ctx.fillRect(20, 20, 120, 80);
</script>
<svg>
Purpose:
- creates vector graphics directly in markup
Important attributes:
widthheightviewBox
Example:
<svg width="120" height="120" viewBox="0 0 120 120">
<circle cx="60" cy="60" r="40" fill="tomato" />
</svg>
Use SVG for:
- icons
- logos
- diagrams
- scalable illustrations
Canvas vs SVG
- canvas is pixel-based and script-driven
- SVG is markup-based and scalable
- canvas is good for fast repeated drawing
- SVG is good for crisp UI graphics and accessible shapes