Graphics: Canvas & SVG
Draw shapes, charts and graphics directly in the browser — two built-in ways with no plugins.
What you will learn
- Draw shapes with SVG
- Understand what <canvas> is for
- Choose between SVG and Canvas
SVG — shapes as tags
SVG (Scalable Vector Graphics) lets you draw shapes with tags. SVG stays razor-sharp at any size — perfect for logos and icons.
<svg width="220" height="120">
<rect x="10" y="10" width="90" height="90" fill="#4338ca" rx="10"></rect>
<circle cx="160" cy="55" r="45" fill="#06b6d4"></circle>
<text x="20" y="115" fill="#333">SVG shapes</text>
</svg>Inside <svg> each shape is its own tag: <rect> draws a rectangle at position x/y with a width/height (and rx="10" rounds its corners), <circle> draws a circle from a centre (cx/cy) and radius r, and <text> places words. fill sets each shape’s colour. Because it is made of tags and maths, it stays sharp at any zoom.
Note: Output: A rounded indigo square on the left and a cyan circle on the right, with the label “SVG shapes” underneath.
Canvas — draw with JavaScript
The <canvas> element is a blank drawing surface you control with JavaScript. It is great for games, charts and animation. (It needs JS, which you will learn next.)
<canvas id="c" width="220" height="100" style="border:1px solid #ccc"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.fillStyle = '#4338ca';
ctx.fillRect(20, 20, 80, 60);
ctx.fillStyle = '#06b6d4';
ctx.beginPath();
ctx.arc(160, 50, 35, 0, Math.PI * 2);
ctx.fill();
</script>The <canvas> tag is just a blank rectangle; the drawing happens in the <script>. getContext('2d') gives a “pen” called ctx. We set fillStyle to a colour, fillRect paints a rectangle, then change colour and use arc + fill to paint a circle. Unlike SVG, these are painted as pixels, so the picture only exists once the JavaScript runs.
Note: Output: An indigo rectangle and a cyan circle drawn inside a bordered box — painted by the JavaScript, not by tags.
| SVG | Canvas | |
|---|---|---|
| Made of | Tags (vector) | Pixels (drawn by JS) |
| Scales sharply | ✅ Yes | ❌ Can blur |
| Best for | Logos, icons, charts | Games, heavy animation |
Q. You need a logo that stays sharp at any size. Which fits best?
✍️ Practice
- Draw a simple scene with SVG: a sky rectangle, a sun circle and some text.
- Copy the canvas example and change the colours and shapes.
🏠 Homework
- Recreate the CodingClave logo idea as a small SVG (rectangle + circle + text).