On this page13 sections
Lecture 039: Canvas
| Category | 7: Interactive Elements, Graphics & Media |
| Lecture | 039 of 048 |
| Estimated video length | 14 min |
| Target | HTML5 · any modern browser |
| Level | Beginner |
<canvas>is a blank drawing area. On its own it shows nothing: you draw on it with JavaScript, pixel by pixel, shape by shape. It powers charts, photo editors and browser games.
Learning Objectives
- Add a
<canvas>and get its 2D drawing context - Draw rectangles, lines, circles and text
- Fill with colours and gradients, and draw images
- Animate a drawing
1. The Canvas and Its Context
Example
<canvas id="c" width="300" height="150" style="border: 1px solid #ced4da;">
Your browser does not support canvas.
</canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.fillStyle = '#4c6ef5';
ctx.fillRect(20, 20, 120, 80); // x, y, width, height
</script>- Set the size with the
widthandheightattributes (CSS sizes would stretch the drawing). (0, 0)is the top-left corner;ygrows downwards.
2. Rectangles
<canvas id="c" width="300" height="120"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.fillStyle = '#ffd43b'; ctx.fillRect(10, 10, 80, 80); // filled
ctx.strokeStyle = '#e8590c'; ctx.lineWidth = 4;
ctx.strokeRect(110, 10, 80, 80); // outline
ctx.fillStyle = '#2f9e44'; ctx.fillRect(210, 10, 80, 80);
ctx.clearRect(230, 30, 40, 40); // erase a hole
</script>3. Lines and Paths
A path is a shape you build step by step, then stroke() (outline) or fill().
Example
<canvas id="c" width="300" height="150"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.beginPath();
ctx.moveTo(20, 130); // start (no line drawn)
ctx.lineTo(150, 20); // draw to here
ctx.lineTo(280, 130);
ctx.closePath(); // back to the start
ctx.fillStyle = '#d0ebff';
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = '#1864ab';
ctx.stroke();
</script>4. Circles
arc(x, y, radius, startAngle, endAngle), with angles in radians (a full circle is 2 * Math.PI).
Example
<canvas id="c" width="300" height="150"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.beginPath();
ctx.arc(75, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#ff8787'; ctx.fill();
ctx.beginPath();
ctx.arc(210, 75, 50, 0, Math.PI); // half circle
ctx.strokeStyle = '#7048e8'; ctx.lineWidth = 5; ctx.stroke();
</script>5. Text
Example
<canvas id="c" width="320" height="110"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
ctx.font = 'bold 32px Arial';
ctx.fillStyle = '#212529';
ctx.fillText('Hello Canvas', 20, 45);
ctx.strokeStyle = '#e8590c';
ctx.strokeText('Outlined text', 20, 90);
</script>6. Gradients
Example
<canvas id="c" width="300" height="120"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
const g = ctx.createLinearGradient(0, 0, 300, 0);
g.addColorStop(0, '#f76707');
g.addColorStop(1, '#ae3ec9');
ctx.fillStyle = g;
ctx.fillRect(10, 10, 280, 100);
</script>createRadialGradient(x0, y0, r0, x1, y1, r1) makes a circular gradient.
7. Images
Example
<canvas id="c" width="300" height="180"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
const img = new Image();
img.onload = () => {
ctx.drawImage(img, 0, 0, 300, 180);
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(0, 140, 300, 40);
ctx.fillStyle = 'white'; ctx.font = '18px Arial';
ctx.fillText('Drawn on a canvas', 10, 166);
};
img.src = 'https://picsum.photos/id/1039/300/180';
</script>Wait for onload before drawing, or there's nothing to draw yet.
8. A Simple Animation
Example: a bouncing ball:
<canvas id="c" width="300" height="150" style="border: 1px solid #ced4da;"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
let x = 30, y = 30, dx = 2.5, dy = 2;
function frame() {
ctx.clearRect(0, 0, 300, 150); // wipe the last frame
ctx.beginPath(); ctx.arc(x, y, 15, 0, 2 * Math.PI);
ctx.fillStyle = '#12b886'; ctx.fill();
if (x < 15 || x > 285) dx = -dx; // bounce off the sides
if (y < 15 || y > 135) dy = -dy;
x += dx; y += dy;
requestAnimationFrame(frame); // draw again next frame
}
frame();
</script>Common Beginner Mistakes
1. Sizing the canvas with CSS only. The drawing gets stretched and blurry. Use the width and height attributes.
2. Forgetting beginPath(). New shapes join on to the previous path.
3. Degrees instead of radians. arc(…, 0, 360) doesn't do what you expect. Use 2 * Math.PI.
4. Drawing an image before it loads. Draw inside img.onload.
Practice Questions
- What do you need to call to start drawing on a canvas?
- Where is the point
(0, 0)on a canvas? - Draw a red filled square 50×50 at (10, 10).
- Which method draws a circle, and what is a full circle's end angle?
- What does
clearRectdo? - Why use
requestAnimationFramefor animation?
Practice Answers
canvas.getContext('2d')- The top-left corner.
ctx.fillStyle = 'red'; ctx.fillRect(10, 10, 50, 50);arc(); the end angle is2 * Math.PI.- It erases a rectangle, making it transparent.
- It draws smoothly in step with the screen, and pauses when the tab is hidden.
Key Takeaways
<canvas>is a drawing surface; JavaScript does the drawing viagetContext('2d').- Rectangles, paths, arcs, text, gradients and images are the building blocks.
- Size with attributes;
(0, 0)is top-left; angles are in radians. - Animate with
clearRect+ redraw insiderequestAnimationFrame.