Chapter 33: Canvas Tutorial
First — What is “Canvas” actually? (Clear definition)
Canvas (in web development) means the <canvas> HTML element — it is a blank drawing board inside your webpage where you can draw anything using JavaScript code.
Think of it like:
- Paper + pencil in real life → you draw lines, circles, text, images by hand
- <canvas> + JavaScript → you draw the same things (lines, circles, rectangles, text, images, animations, games, charts) using code
Main points everyone must remember from day 1:
- Canvas is pixel-based (not vector like SVG) → zoom too much = can become pixelated
- Canvas is programmatic → every drawing command is written in JavaScript
- Canvas is very fast for animations, games, data visualization, image editing
- Canvas is very different from SVG — we’ll compare at the end
Step 1 – Your First Canvas “Hello World” (Copy-Paste & Run Now!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Hello World</title> <style> canvas { border: 2px solid #333; background: #f8f9fa; } </style> </head> <body> <h1>My First Canvas Drawing</h1> <canvas id="myCanvas" width="600" height="400"></canvas> <script> // 1. Get the canvas element const canvas = document.getElementById('myCanvas'); // 2. Get the 2D drawing context (this is the "pencil") const ctx = canvas.getContext('2d'); // 3. Start drawing! // Draw a blue rectangle (background) ctx.fillStyle = '#3498db'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw a yellow circle in center ctx.fillStyle = '#f1c40f'; ctx.beginPath(); ctx.arc(300, 200, 80, 0, Math.PI * 2); // centerX, centerY, radius, startAngle, endAngle ctx.fill(); // Draw red text ctx.font = 'bold 50px Arial'; ctx.fillStyle = 'red'; ctx.textAlign = 'center'; ctx.fillText('Hello Canvas!', 300, 220); </script> </body> </html> |
What you see:
- Big blue background
- Yellow circle in center
- Red text “Hello Canvas!”
This is your starting point — every canvas drawing begins with these 3 lines:
|
0 1 2 3 4 5 6 7 8 |
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // Now ctx is your drawing tool |
Step 2 – All Important Basic Drawing Commands (With Examples)
A. Fill & Stroke Basics
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Fill rectangle (solid color) ctx.fillStyle = 'orange'; ctx.fillRect(50, 50, 200, 120); // Stroke (border only) ctx.strokeStyle = 'purple'; ctx.lineWidth = 8; ctx.strokeRect(300, 50, 200, 120); // Clear part of canvas (erase) ctx.clearRect(100, 100, 100, 100); |
B. Lines & Paths
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
ctx.beginPath(); // Start a new path ctx.moveTo(50, 200); // Move pen without drawing ctx.lineTo(250, 200); // Draw line to this point ctx.lineTo(150, 100); // Another line ctx.closePath(); // Connect back to start (optional) ctx.strokeStyle = 'green'; ctx.lineWidth = 10; ctx.lineCap = 'round'; // butt, round, square ctx.stroke(); // Actually draw the stroke |
C. Curves (Quadratic & Bezier)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Quadratic curve (1 control point) ctx.beginPath(); ctx.moveTo(50, 150); ctx.quadraticCurveTo(150, 50, 250, 150); // controlX, controlY, endX, endY ctx.strokeStyle = 'blue'; ctx.lineWidth = 8; ctx.stroke(); // Cubic Bezier (2 control points – smoother) ctx.beginPath(); ctx.moveTo(50, 250); ctx.bezierCurveTo(100, 100, 200, 300, 250, 250); ctx.strokeStyle = 'red'; ctx.stroke(); |
D. Text (Very Important)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
ctx.font = 'bold 40px Arial'; ctx.fillStyle = 'darkgreen'; ctx.textAlign = 'center'; // start, end, center, left, right ctx.textBaseline = 'middle'; // top, hanging, middle, alphabetic, ideographic, bottom ctx.fillText('Welcome!', 200, 300); // Stroke text (outline) ctx.strokeStyle = 'black'; ctx.lineWidth = 3; ctx.strokeText('Welcome!', 200, 350); |
E. Images & Photos
|
0 1 2 3 4 5 6 7 8 9 10 |
const img = new Image(); img.src = 'https://picsum.photos/300/200'; img.onload = () => { ctx.drawImage(img, 50, 50, 300, 200); // image, dx, dy, dWidth, dHeight }; |
Step 3 – Canvas vs SVG (Quick Comparison Table – Very Important for Exams)
| Feature | Canvas (<canvas>) | SVG (<svg>) |
|---|---|---|
| Type | Pixel / raster-based | Vector / math-based |
| Zoom quality | Can become pixelated when enlarged | Always sharp, no matter zoom |
| DOM elements | One single element (no child elements in DOM) | Many child elements (rect, circle, path, text…) |
| Animation | Very fast for complex animations / games | Good for simple to medium animations |
| Interactivity | Needs JavaScript to detect clicks / hover | Native click/hover on individual shapes |
| File size (complex) | Small (just JS code) | Can become large with many elements |
| Editing | Hard to edit individual parts after drawing | Easy — change attributes on any element |
| Best for | Games, real-time charts, image editing, 3D effects | Icons, logos, illustrations, diagrams, maps |
Step 4 – Teacher’s Quick Tips (Hyderabad Student Style 😄)
- Always get context first: ctx = canvas.getContext(‘2d’)
- beginPath() → very important before drawing lines/curves — prevents connecting to previous path
- Use save() and restore() when you want to change styles temporarily
|
0 1 2 3 4 5 6 7 8 9 |
ctx.save(); ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 50, 50); ctx.restore(); // back to previous styles |
- For animation → use requestAnimationFrame (smooth 60fps)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
function animate() { // clear canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // draw something ctx.fillRect(frame++, 100, 50, 50); requestAnimationFrame(animate); } requestAnimationFrame(animate); |
Understood the Canvas Tutorial basics now? This is your starting point — from here you can build games, charts, photo editors, animations, anything.
Tell me what you want next — we can go deeper in any direction:
- Full bouncing ball animation?
- Mouse drawing app (paint-like)?
- Clock with moving hands?
- Image filters (blur, grayscale) on canvas?
- Canvas vs SVG full project comparison?
- Or 20-question Canvas quiz like we did for SVG?
Just say — we keep building your skills step by step! 🚀
