Introduction
The HTML5 <canvas> element allows you to draw graphics,
animations, game scenes, shapes, charts, and more — all using JavaScript.
Canvas is a pixel-based drawing surface controlled by code.
1. Basic Canvas Setup
2. Drawing Rectangles
// Filled rectangle
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 150, 100);
// Outline rectangle
ctx.strokeStyle = "white";
ctx.strokeRect(250, 50, 150, 100);
3. Drawing Lines
ctx.beginPath();
ctx.moveTo(50, 200);
ctx.lineTo(300, 200);
ctx.strokeStyle = "cyan";
ctx.lineWidth = 3;
ctx.stroke();
4. Drawing Circles
ctx.beginPath();
ctx.arc(200, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = "yellow";
ctx.fill();
5. Drawing Text
ctx.font = "30px Arial";
ctx.fillStyle = "lime";
ctx.fillText("Hello Canvas!", 50, 50);
6. Loading Images
const img = new Image();
img.src = "car.png";
img.onload = () => {
ctx.drawImage(img, 100, 100, 200, 120);
};
7. Simple Animation Loop
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "orange";
ctx.fillRect(x, 100, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();
8. Common Use Cases
- Game graphics
- Interactive animations
- Drawing apps
- Charting libraries
- Physics simulations
Summary
Canvas gives you full pixel-level drawing power using JavaScript. You now know how to draw shapes, text, images, and create animations — the foundation for games and advanced graphics.