🖼️ Module 14 · Advanced Elements🔴 AdvancedLESSON 49

Canvas Basics

⏱️ 17 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Course progress52%
🎯 What you'll learn: The <canvas> element, getting a 2d drawing context, drawing shapes/text/images, and building simple animations.

canvas vs SVG

<canvas> is a raster drawing surface — everything you draw becomes pixels, with no memory of individual shapes as DOM elements. This makes it great for pixel-level control, games, and per-frame animation, but you lose SVG's easy CSS styling and built-in accessibility.

canvas-setup.html
HTML
<canvas id="myCanvas" width="300" height="150"></canvas>

<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
</script>

Drawing Shapes & Text

canvas-drawing.html
HTML
<script>
ctx.fillStyle = '#2de8c0';
ctx.fillRect(20, 20, 100, 60); // filled rectangle

ctx.beginPath();
ctx.arc(200, 50, 30, 0, Math.PI * 2); // circle
ctx.fillStyle = '#fb923c';
ctx.fill();

ctx.font = '20px sans-serif';
ctx.fillStyle = 'white';
ctx.fillText('Hello Canvas', 20, 120);
</script>
MethodDraws
fillRect(x,y,w,h)A filled rectangle
arc(x,y,r,start,end)A circle/arc path
fillText(text,x,y)Text at a position
drawImage(img,x,y)An image onto the canvas

Simple Animation With requestAnimationFrame

Animating canvas means clearing it and redrawing every frame. requestAnimationFrame schedules the next frame in sync with the browser's refresh rate — smoother and more efficient than setInterval.

canvas-animation.html
HTML
<script>
let x = 0;
function frame() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#a78bfa';
  ctx.fillRect(x, 60, 30, 30);
  x = (x + 2) % canvas.width;
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
⚠️
Always clearRect() before redrawing
Canvas doesn't automatically erase the previous frame — forgetting clearRect() leaves a smeared trail of every previous position drawn on top of each other.
🧩 Knowledge Check — Lesson 49
5 questions to test your understanding.
1. Is canvas raster-based or vector-based?
2. What method returns the drawing context?
3. What draws a filled rectangle?
4. Why is requestAnimationFrame preferred over setInterval for animation?
5. What happens if you forget clearRect() before redrawing each frame?
💪
Coding Challenge — Lesson 49
Apply what you learned · Advanced Level
Challenge: Build a Bouncing Ball

Build a canvas with a circle that moves horizontally each frame using requestAnimationFrame, clearing the canvas before each redraw, and reversing direction when it hits either edge.
💡 Show hints if you're stuck
  • Track a velocity variable and flip its sign when x hits 0 or canvas.width.
Finished this lesson?
Mark it complete to track your progress.
🎉

Lesson 49 Complete!

You can now draw and animate on canvas. Up next: Progress Elements!

Lesson 49 of 62Module 14 — Advanced Elements