JavaScript
Summary - Canvas
Build a bouncing ball animation with fillRect and requestAnimationFrame.
Summary - Canvas
In this group you learned the canvas basics. You select the element with getElementById and get the drawing context with getContext('2d').
fillRect draws filled rectangles, strokeRect outlines, clearRect erases. With beginPath, moveTo, lineTo and closePath you build a path, and stroke or fill makes it visible. requestAnimationFrame sets up a smooth animation loop.
Exercise Bouncing ball animation
Build a bouncing ball animation. Initialize with let y = 10 and let dy = 3. In the draw function, clear the screen with ctx.clearRect(0, 0, canvas.width, canvas.height) and draw the ball with ctx.fillRect(20, y, 20, 20). When the ball hits the bottom (y + 20 >= canvas.height) or the top (y <= 0), reverse direction with dy = -dy. Then advance with y += dy and keep the loop going with requestAnimationFrame(draw).
Show example solution
let y = 10;
let dy = 3;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(20, y, 20, 20);
if (y + 20 >= canvas.height || y <= 0) {
dy = -dy;
}
y += dy;
requestAnimationFrame(draw);
}
draw();
Where canvas is used
The canvas is used for games, charts, data visualization and interactive drawing. For example, a bouncing ball game, a simple line chart, or a mouse-driven drawing app are all possible.
The basics you learned are: the coordinate system, rectangle and path drawing, and the animation loop. In the next step you will combine them and draw a green filled triangle.
Exercise Green filled triangle
Draw a triangle and fill it. Start the path with ctx.beginPath(). Mark the three corners with ctx.moveTo(50, 10), ctx.lineTo(90, 80) and ctx.lineTo(10, 80). Close the path with ctx.closePath(). Set the fill color to green with ctx.fillStyle = 'green' and fill the inside with ctx.fill().
Show example solution
ctx.beginPath();
ctx.moveTo(50, 10);
ctx.lineTo(90, 80);
ctx.lineTo(10, 80);
ctx.closePath();
ctx.fillStyle = 'green';
ctx.fill();
Test yourself
-
Which method clears a region on the canvas and makes it transparent?
- fillRect
- strokeRect
- clearRect
- beginPath
Show answer
clearRect — Correct! clearRect clears a rectangular region and makes it transparent.
-
Match the summary
- getContext
- get context
- fillRect
- fill rectangle
- beginPath
- start path
- requestAnimationFrame
- animation loop
Next lesson: Project: Canvas mini game