Chapter 35: Canvas Drawing
Canvas Drawing in the most detailed, step-by-step, human-teacher way possible. π
Iβm going to explain everything very slowly, like Iβm sitting right next to you in a Hyderabad computer lab or coaching center. No rushing, no assuming you already know something, full classroom style β with lots of copy-paste examples you can run right now, clear explanations, and real tips students always ask about.
1. What is βCanvas Drawingβ actually?
Canvas Drawing means using the HTML <canvas> element + JavaScript to draw graphics directly on the screen pixel by pixel β lines, rectangles, circles, curves, text, images, gradients, shadows, animations, charts, games, photo effects, and almost anything visual you can imagine.
Think of it like this:
- Paper + pencil in real life β you draw whatever you want by hand
- <canvas> + JavaScript β you draw the same things (shapes, text, photos, animations) using code commands
Important things to remember from day one:
- Canvas is pixel-based (not vector like SVG) β if you zoom the browser a lot, drawings can become pixelated
- All drawing happens through JavaScript β there are no child tags inside <canvas> like <circle> or <rect>
- You get one drawing tool called the context (usually 2D context) β think of it as your pencil, brush, paint bucket, eraser, ruler, all in one
- Canvas is very fast for real-time animations, games, charts, image editing
- Canvas is very different from SVG β weβll compare properly at the end
2. Your Very First Canvas Drawing β Hello World (Copy-Paste & Run Right Now!)
Create a file called canvas-drawing-hello.html and paste this complete code:
|
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas Drawing β Hello World</title> <style> canvas { border: 4px solid #2c3e50; background: #ecf0f1; display: block; margin: 30px auto; box-shadow: 0 4px 15px rgba(0,0,0,0.2); } h1 { text-align: center; color: #34495e; } </style> </head> <body> <h1>My First Canvas Drawing β Let's Start!</h1> <canvas id="myCanvas" width="700" height="450"></canvas> <script> // Step 1: Find the <canvas> element in the HTML const canvas = document.getElementById('myCanvas'); // Step 2: Get the 2D drawing context β this is your "pencil / brush" const ctx = canvas.getContext('2d'); // Step 3: Start drawing! // A β Background rectangle (sky blue) ctx.fillStyle = '#3498db'; ctx.fillRect(0, 0, canvas.width, canvas.height); // B β Big yellow sun in top-right ctx.fillStyle = '#f1c40f'; ctx.beginPath(); ctx.arc(550, 100, 80, 0, Math.PI * 2); // centerX, centerY, radius, startAngle, endAngle ctx.fill(); // C β Black border around sun ctx.strokeStyle = '#d35400'; ctx.lineWidth = 10; ctx.stroke(); // D β Green grass at bottom ctx.fillStyle = '#27ae60'; ctx.fillRect(0, 300, canvas.width, 150); // E β Brown tree trunk ctx.fillStyle = '#8d5524'; ctx.fillRect(150, 220, 40, 120); // F β Green tree leaves (three circles) ctx.fillStyle = '#2ecc71'; ctx.beginPath(); ctx.arc(170, 180, 60, 0, Math.PI * 2); ctx.arc(130, 220, 50, 0, Math.PI * 2); ctx.arc(210, 220, 50, 0, Math.PI * 2); ctx.fill(); // G β Big white text ctx.font = 'bold 60px Arial'; ctx.fillStyle = 'white'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('Canvas Drawing!', 350, 100); // H β Small signature text ctx.font = 'italic 24px Georgia'; ctx.fillStyle = '#ecf0f1'; ctx.fillText('Made with <canvas> + JavaScript', 350, 420); console.log("Drawing finished! π¨ You did it!"); </script> </body> </html> |
What you see:
- Sky-blue background
- Yellow sun with border
- Green grass
- Simple tree (trunk + leaves)
- Big white title + small signature
This is your starting ritual β every canvas drawing 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 drawing tool β everything starts from here |
3. Core Drawing Commands β One by One with Copy-Paste Snippets
A. Rectangles (the easiest shape)
|
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.8)'; // semi-transparent red ctx.fillRect(100, 100, 250, 150); // Only border (stroke) ctx.strokeStyle = '#8e44ad'; ctx.lineWidth = 12; ctx.strokeRect(400, 100, 200, 150); // Rounded rectangle (modern browsers) ctx.beginPath(); ctx.roundRect(100, 300, 250, 100, 40); // x, y, width, height, corner radius ctx.fillStyle = '#3498db'; 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(); // Always start a new path ctx.moveTo(50, 350); // Move pen here (no line yet) ctx.lineTo(200, 200); // Draw straight line to here ctx.lineTo(350, 350); // Another line ctx.closePath(); // Optional: connect back to start ctx.strokeStyle = '#e67e22'; ctx.lineWidth = 18; ctx.lineCap = 'round'; // butt (default), round, square ctx.lineJoin = 'round'; // miter (sharp), round, bevel ctx.stroke(); // Actually draw the lines |
C. Curves (Quadratic & Bezier β very important)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Quadratic curve (1 control point β simple bend) ctx.beginPath(); ctx.moveTo(50, 380); ctx.quadraticCurveTo(200, 280, 350, 380); // controlX, controlY, endX, endY ctx.strokeStyle = 'purple'; ctx.lineWidth = 12; ctx.stroke(); // Cubic Bezier curve (2 control points β very smooth) ctx.beginPath(); ctx.moveTo(50, 420); ctx.bezierCurveTo(100, 320, 250, 500, 350, 420); ctx.strokeStyle = 'cyan'; ctx.lineWidth = 10; ctx.stroke(); |
D. Circles, Arcs & Pie Slices
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
ctx.beginPath(); ctx.arc(450, 250, 70, 0, Math.PI * 2); // full circle ctx.fillStyle = '#f39c12'; ctx.fill(); // Half-circle (pie slice style) ctx.beginPath(); ctx.arc(450, 250, 70, 0, Math.PI); // start 0 to 180Β° ctx.lineTo(450, 250); // back to center ctx.fillStyle = '#e74c3c'; ctx.fill(); |
E. Text β Very Important for Charts, Games, UI
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
ctx.font = 'bold 50px "Segoe UI", Arial'; ctx.fillStyle = '#2c3e50'; ctx.textAlign = 'center'; // start, end, center, left, right ctx.textBaseline = 'middle'; // top, hanging, middle, alphabetic, bottom ctx.fillText('Canvas Power!', 350, 80); // Stroke text (outline only) ctx.strokeStyle = '#c0392b'; ctx.lineWidth = 5; ctx.strokeText('Canvas Power!', 350, 140); |
F. Images / Photos (Very Common in Projects)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const img = new Image(); img.crossOrigin = "anonymous"; // needed for external images img.src = 'https://picsum.photos/600/400'; img.onload = function() { // Draw full image ctx.drawImage(img, 50, 50, 600, 400); // Draw cropped part ctx.drawImage(img, 150, 100, 300, 300, 200, 100, 300, 300); }; |
4. Canvas vs SVG β Quick Comparison Table (Exam & Interview 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 1000s of points, photo editing | Icons, logos, illustrations, diagrams, maps |
5. Teacherβs Most Important Tips (Hyderabad Student Style)
- Always set width & height on the <canvas> tag itself (not just CSS) β otherwise drawing gets stretched / blurry
- Use ctx.save() and ctx.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 smooth animation: use requestAnimationFrame (60 fps)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); // draw moving object ctx.fillRect(x += 2, 100, 50, 50); requestAnimationFrame(animate); } requestAnimationFrame(animate); |
- Common mistake #1: Forget beginPath() before lines/curves β connects to previous drawing
- Common mistake #2: Use CSS width/height instead of HTML attributes β blurry / wrong scale
Understood Canvas Drawing basics now? This is your strong foundation β from here you can build paint apps, games, animated charts, image editors, anything.
Tell me what you want next β we can go deeper in any direction:
- 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 style)?
- Or 20-question Canvas quiz like we did for SVG?
Just say β we keep going step by step together! π
