⚡ Lesson 26 of 30
Canvas & 2D Graphics
Draw shapes, text, images, and animations on the HTML5 Canvas element using JavaScript.
Setting Up Canvas
Add a <canvas> element to your HTML, then get the 2D drawing context:
Shapes
// Rectangle
ctx.fillStyle = "#f7c948";
ctx.fillRect(50, 50, 200, 100); // x,y,width,height
ctx.strokeStyle = "#ff6b35";
ctx.lineWidth = 3;
ctx.strokeRect(50, 50, 200, 100);
// Circle
ctx.beginPath();
ctx.arc(300, 200, 60, 0, Math.PI * 2); // x,y,radius,start,end
ctx.fillStyle = "#4ecdc4";
ctx.fill();
// Line
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(600, 400);
ctx.strokeStyle = "white";
ctx.stroke();
Text
ctx.font = "bold 48px Space Mono, monospace";
ctx.fillStyle = "#f7c948";
ctx.textAlign = "center";
ctx.fillText("Hello Canvas!", canvas.width / 2, 200);
ctx.font = "24px sans-serif";
ctx.fillStyle = "rgba(255,255,255,0.6)";
ctx.fillText("JavaScript 2026", canvas.width / 2, 250);
Gradients & Paths
// Linear gradient
const grad = ctx.createLinearGradient(0, 0, 600, 0);
grad.addColorStop(0, "#f7c948");
grad.addColorStop(1, "#ff6b35");
ctx.fillStyle = grad;
ctx.fillRect(0, 0, 600, 80);
// Custom path (triangle)
ctx.beginPath();
ctx.moveTo(300, 100);
ctx.lineTo(450, 350);
ctx.lineTo(150, 350);
ctx.closePath();
ctx.fill();
Animation Loop
let angle = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Rotating square
ctx.save();
ctx.translate(300, 200);
ctx.rotate(angle);
ctx.fillStyle = "#f7c948";
ctx.fillRect(-50, -50, 100, 100);
ctx.restore();
angle += 0.02;
requestAnimationFrame(draw); // ~60fps
}
draw();