HTML5 Graphics: SVG & Canvas
HTML5 Graphics: SVG & Canvas (Drawing on the Web) 🎨
Welcome to Topic 10.4 in Chapter 10: Media!
Until now, whenever we wanted to display artwork or illustrations on a webpage, we loaded external image files like .png, .jpg, or .webp.
What happens when a visitor zooms in to 400% on a smartphone? Normal raster photos become blurry and pixelated!
What if you want to:
- Draw a crisp school emblem or logo that stays crystal clear on high-resolution Retina screens?
- Build a dynamic science graph showing pendulum oscillations?
- Build an interactive 2D computer game (like Pong, Flappy Bird, or Snake) right inside the browser?
HTML5 introduced two native graphical powerhouses:
- 1SVG (Scalable Vector Graphics)
- 2HTML5
<canvas>
In this lesson, you will discover how these two technologies work and when to pick each one!
The Real-Life School Analogy: The Geometry Stencil vs The Graph Paper 📐
Think about two common items in your School Geometry & Math Kit:
1. The Plastic Geometry Stencil (SVG)
When you use a plastic circular stencil to trace a circle with a fine-tip pen:
- The shape is defined by pure geometry (a center point and radius $r$).
- If you trace that circle in your pocket diary, it looks sharp.
- If you project that circle onto a giant 50-foot cinema projector screen, the curves remain 100% razor sharp with zero blur!
- That is SVG (Scalable Vector Graphics)!
2. The Math Millimeter Graph Paper (Canvas)
Think of a grid of tiny square millimeters in your mathematics lab manual:
- You color specific coordinate boxes $(x, y)$ with color sketch pens to build a pixelated mosaic image.
- If you hold a magnifying glass over the paper, you see individual colored pixel squares.
- That is HTML5
<canvas>! It gives you a blank grid of pixels where you can paint dynamically using code!
1. Scalable Vector Graphics: <svg> 🛡️
SVG is an XML-based language for describing 2D vector shapes directly inside your HTML document.
Because SVG is made of mathematical equations (lines, curves, and angles), it has infinite resolution — it never blurs, no matter how much you zoom in!
Basic SVG Shapes:
Why Developers Love Inline SVG:
- 1Zero Blurriness: Looks stunning on 4K monitors and mobile phones.
- 2Tiny File Size: A few lines of text replace a 200 KB image file!
- 3Interactive & Stylable: You can change SVG colors on hover using CSS:
- 1Accessible: Screen readers can read
<title>and<desc>tags placed inside SVG.
2. Pixel Drawing & Games: The HTML5 <canvas> 🎮
While SVG is made of independent vector shapes, <canvas> is an empty rectangular pixel board.
You create the board in HTML, and then use JavaScript like an artist's paintbrush to draw lines, circles, text, and animations:
The Canvas Coordinate System 🧭
Always remember how canvas coordinates work:
- $(0, 0)$ is at the top-left corner of the canvas!
- $X$ values increase towards the right →.
- $Y$ values increase downwards ↓ (unlike standard Cartesian school math graphs where $Y$ goes up!).
3. Head-to-Head Comparison: SVG vs Canvas 🥊
| Feature | SVG (Vector Shapes) 📐 | Canvas (Pixel Bitmap) 🖼️ |
|---|---|---|
| Drawing Type | Vector-based (Mathematical formulas) | Raster / Bitmap (Pixel grid) |
| Resolution | Infinite! Never pixelates or blurs. | Fixed resolution. Can blur if stretched. |
| DOM Nodes | Every shape is an HTML DOM element. | A single <canvas> tag (shapes are drawn into memory). |
| CSS Styling | Yes! Can style and animate shapes via CSS. | No CSS styling for individual shapes. |
| Event Handling | Can add onclick directly to individual shapes! | Must manually calculate $(x, y)$ mouse click coordinates. |
| Performance | Slower if rendering thousands of shapes. | Lightning fast! Can render 100,000 particles at 60 FPS. |
| Best Used For | Logos, UI icons, school emblems, charts. | 2D/3D browser games, video processing, canvas drawing tools. |
Complete Real-World Project: School Sports Shield & Scoreboard 🏫
Here is a complete, working HTML webpage featuring a pure SVG School Shield Emblem and an interactive Canvas target score game:
Common Beginner Mistakes & Best Practices ⚠️
| ❌ Common Mistake | ✅ Best Practice | Why It Matters |
|---|---|---|
Setting Canvas size with CSS width/height (style="width: 400px;"). | Always set Canvas dimensions using HTML attributes: <canvas width="400" height="300">. | CSS width stretches the pixel bitmap, causing blurry, distorted graphics! |
| Using Canvas for logos and website icons. | Use SVG for logos and icons. | SVG scales infinitely without blurriness and has a much smaller file size. |
Forgetting ctx.beginPath() before drawing paths on Canvas. | Always call ctx.beginPath() before starting a new shape. | Without beginPath(), previous shapes reconnect and create messy unwanted lines. |
Forgetting accessibility on SVG (aria-label). | Add aria-label or <title> inside <svg> icons. | Screen readers need accessible labels to describe the graphic to visually impaired users. |
| Thinking $(0, 0)$ is at the bottom-left of Canvas. | Remember that $(0, 0)$ is at the top-left corner. | Canvas coordinates increase downwards on the $Y$-axis! |
Quick Summary (Revision Notes) 🧠
- SVG (Scalable Vector Graphics) uses mathematical formulas (lines, curves, polygons) to create infinite-resolution graphics that never blur.
- Common SVG shape tags:
<rect>,<circle>,<line>,<polygon>, and<text>. - Individual SVG elements can be styled with CSS and receive mouse click events.
- HTML5
<canvas>is an empty pixel-based bitmap grid manipulated dynamically with JavaScript via its 2D context (getContext('2d')). - Canvas coordinate $(0, 0)$ starts at the top-left corner; $X$ increases rightward, $Y$ increases downward.
- When to choose SVG: Logos, UI icons, badges, school crests, and static charts.
- When to choose Canvas: 2D browser games, high-frequency particle animations, and photo filter manipulation.
Practice Quiz
Test your understanding with these multiple-choice questions:
1. What happens when you zoom in on an SVG graphic by 500%?
A. It becomes pixelated and blurry B. It remains 100% razor sharp with zero loss in visual quality C. The colors invert into black and white D. The browser crashes Answer: B Explanation: SVG graphics are mathematical vector descriptions. They re-render smoothly at any scale or zoom level without losing quality.
2. Which tag is used in SVG to draw a circle with a center point and radius?
A. <round> B. <circle cx="..." cy="..." r="..."> C. <dot> D. <arc> Answer: B Explanation: The <circle> tag in SVG defines a circle using center coordinates cx and cy, and radius r.
3. Where is the origin coordinate $(0, 0)$ located on an HTML5 <canvas>?
A. In the exact center B. At the bottom-left corner C. At the top-left corner D. At the bottom-right corner Answer: C Explanation: The Canvas 2D rendering grid begins with $(0, 0)$ at the top-left corner. $X$ increases to the right, and $Y$ increases downwards.
4. Which JavaScript method retrieves the drawing context used to paint on a <canvas>?
A. canvas.getPaintbrush() B. canvas.getContext('2d') C. canvas.createTool() D. canvas.drawContext() Answer: B Explanation: The .getContext('2d') method returns the 2D rendering context object containing all drawing functions (like fillRect, arc, stroke).
5. Why should you prefer Canvas over SVG when building a fast-paced 2D action game with 5,000 moving objects?
A. SVG cannot display colors B. Canvas renders directly into a pixel bitmap in memory, making it much faster for thousands of moving objects C. SVG only works on desktop computers D. Canvas does not require electricity Answer: B Explanation: Each SVG element creates a DOM node, which slows down the browser when thousands of objects move simultaneously. Canvas draws directly to pixels with high performance.
Hands-on Practice Challenge 🎯
Open VS Code and create a file named creative-graphics-lab.html.
Your Challenge:
Build a School Science & Sports Graphic Studio:
- 1SVG School Crest (Vector):
- Create an
<svg width="200" height="200">. - Draw a blue circle base:
<circle cx="100" cy="100" r="80" fill="#0A2540" />. - Add a smaller white inner circle:
<circle cx="100" cy="100" r="70" fill="white" />. - Place your school initials inside with
<text x="100" y="110" text-anchor="middle" fill="#FF6B00" font-size="28" font-weight="bold">MSK</text>.
- 1Canvas Cricket Pitch (Raster):
- Create a
<canvas id="pitch" width="300" height="200">. - Using JavaScript, draw a green cricket field background with
ctx.fillStyle = '#2d6a4f'; ctx.fillRect(0, 0, 300, 200);. - Draw a rectangular tan cricket pitch in the center:
ctx.fillStyle = '#e9c46a'; ctx.fillRect(100, 20, 100, 160);. - Draw three white cricket stumps using lines or thin rectangles.
Open the file in your browser to admire your custom vector badge and painted canvas pitch!
Forms & Input Types
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Iframes & Web Embeds | Forms & Input Types |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.