Chapter 34: Canvas Tutorial
Canvas Tutorial from absolute zero to strong intermediate level.
I’m going to explain everything very slowly, like I’m your favorite patient teacher sitting next to you in a Hyderabad computer lab or coaching center. We will go step-by-step, in simple everyday English, with tons of copy-paste examples you can run immediately. No rushing, no assuming you already know something — full teacher mode.
1. What is <canvas> actually? (Clear definition first)
The <canvas> tag is a blank rectangular drawing board built into every modern web browser.
You give it a width and height (in pixels), then use JavaScript to draw on it — lines, rectangles, circles, text, images, curves, gradients, animations, games, charts, photo filters… almost anything visual.
Key points to remember forever:
- Canvas is pixel-based (not vector like SVG) → if you zoom the page a lot, drawings can look pixelated
- All drawing happens through JavaScript — there are no child tags like <circle> or <rect> inside <canvas>
- You get one drawing context (usually 2D) — think of it as your pencil/brush/paint bucket
- Canvas is very fast for real-time animations, games, data visualization, image manipulation
- Canvas is very different from SVG — we’ll compare properly at the end
2. Your Very First Canvas – Hello World (Copy-Paste & Run Right Now!)
Create a file called canvas-hello.html and paste this:
|
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Tutorial – Hello World</title> <style> canvas { border: 3px solid #2c3e50; background: #ecf0f1; display: block; margin: 20px auto; } </style> </head> <body> <h1>My First Canvas Drawing</h1> <p>Open developer tools (F12) and watch the console if something goes wrong.</p> <canvas id="myFirstCanvas" width="600" height="400"></canvas> <script> // Step 1: Find the canvas element in HTML const canvas = document.getElementById('myFirstCanvas'); // Step 2: Get the 2D drawing context (this is your "pencil") const ctx = canvas.getContext('2d'); // Step 3: Start drawing! // Background – light blue rectangle covering whole canvas ctx.fillStyle = '#3498db'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Yellow circle in the center ctx.fillStyle = '#f1c40f'; ctx.beginPath(); ctx.arc(300, 200, 100, 0, Math.PI * 2); // cx, cy, radius, start angle, end angle ctx.fill(); // Black border around circle ctx.strokeStyle = '#2c3e50'; ctx.lineWidth = 8; ctx.stroke(); // Big white text ctx.font = 'bold 60px Arial'; ctx.fillStyle = 'white'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('Hello Canvas!', 300, 200); console.log("Drawing complete! 🎨"); </script> </body> </html> |
What you see:
- Light blue background
- Big yellow circle with black border
- White text “Hello Canvas!” centered
This is your starting ritual — every canvas project begins with these three lines:
|
0 1 2 3 4 5 6 7 8 |
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // Now ctx is your paintbrush |
3. Core Drawing Commands – With Copy-Paste Snippets
A. Rectangles (fill & stroke)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Filled rectangle ctx.fillStyle = 'rgba(231, 76, 60, 0.7)'; // red with 70% opacity ctx.fillRect(50, 50, 200, 120); // Only border (stroke) ctx.strokeStyle = '#27ae60'; ctx.lineWidth = 10; ctx.strokeRect(300, 50, 200, 120); // Rounded rectangle (modern browsers) ctx.beginPath(); ctx.roundRect(50, 200, 200, 100, 30); // x, y, w, h, radius ctx.fillStyle = '#8e44ad'; ctx.fill(); |
B. Lines & Paths (the most flexible)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
ctx.beginPath(); ctx.moveTo(100, 300); // start here (no line yet) ctx.lineTo(200, 100); // draw to here ctx.lineTo(300, 300); // draw to here ctx.closePath(); // connect back to start ctx.strokeStyle = '#e67e22'; ctx.lineWidth = 15; ctx.lineCap = 'round'; // ends look smooth ctx.lineJoin = 'round'; // corners look smooth ctx.stroke(); |
C. Curves
|
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, 350); ctx.quadraticCurveTo(150, 250, 250, 350); ctx.strokeStyle = 'purple'; ctx.lineWidth = 12; ctx.stroke(); // Cubic Bezier (2 control points – very smooth) ctx.beginPath(); ctx.moveTo(50, 380); ctx.bezierCurveTo(100, 300, 200, 450, 250, 380); ctx.strokeStyle = 'cyan'; 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 48px "Segoe UI", Arial'; ctx.fillStyle = '#2c3e50'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('Welcome to Canvas!', 300, 100); // Outline text ctx.strokeStyle = '#e74c3c'; ctx.lineWidth = 4; ctx.strokeText('Welcome to Canvas!', 300, 160); |
E. Images & Photos
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const img = new Image(); img.crossOrigin = "anonymous"; // needed for external images img.src = 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800'; img.onload = function() { // Draw full image ctx.drawImage(img, 100, 100, 400, 300); // Draw part of image (crop) // ctx.drawImage(img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); ctx.drawImage(img, 200, 100, 200, 200, 50, 50, 200, 200); }; |
4. Canvas vs SVG – Quick Comparison Table (Exam Favorite)
| Question / Feature | Canvas (<canvas>) | SVG (<svg>) |
|---|---|---|
| Technology | Pixel / bitmap | Vector / mathematical |
| Zoom quality | Can become pixelated | Always perfectly sharp |
| DOM structure | One single element (no child tags) | Many child elements (rect, circle, path, text…) |
| Animation performance | Extremely fast (games, real-time) | Good for simple–medium animations |
| Interactivity | Must code click/hover detection manually | Native click/hover on individual elements |
| File size (complex scene) | Usually smaller (just JS code) | Can become large with thousands of elements |
| Editing after drawing | Hard — pixels are “baked” | Easy — change attributes anytime |
| Best for | Games, charts with thousands of points, photo editing, 3D effects | Icons, logos, illustrations, diagrams, maps |
5. Teacher’s Quick Tips (Hyderabad Student Style)
- Always set canvas width & height attributes (not just CSS) — otherwise drawing gets scaled wrong
- Use ctx.save() and ctx.restore() when changing 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 state |
- For smooth animation loop: use requestAnimationFrame
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
function loop() { // clear ctx.clearRect(0, 0, canvas.width, canvas.height); // draw moving object ctx.fillRect(x++, 100, 50, 50); requestAnimationFrame(loop); } requestAnimationFrame(loop); |
- Common mistake #1: Forget beginPath() before lines/curves → connects to previous drawing
- Common mistake #2: Use CSS width/height instead of HTML attributes → blurry drawing
Understood the Canvas Tutorial basics now? This is your strong foundation — from here you can build paint apps, games, animated charts, image editors, anything.
Tell me honestly — what do you want next?
- Full bouncing ball + gravity animation?
- Mouse drawing / paint app?
- Analog clock with moving hands?
- Image filters (blur, grayscale, invert) on canvas?
- Canvas game starter (Pong or Flappy Bird style)?
- 20-question Canvas quiz like we did for SVG?
Just say the word — we keep going deeper together! 🚀
