HTML Canvas API

πŸ–ŒοΈ Introduction to the HTML Canvas API

The <canvas> element and its API allow you to draw graphics, animations, and visual effects dynamically using JavaScript. It provides a powerful way to create 2D shapes, images, charts, games, and more β€” all rendered directly in the browser. πŸ–ΌοΈ

>>β€œWith Canvas, your imagination becomes pixels.” 🎨

πŸ“Œ What is the Canvas Element?

The HTML <canvas> tag defines a rectangular area on a webpage where you can draw graphics using JavaScript. It acts like a digital drawing board.

Basic Canvas Element

<canvas id="myCanvas" width="400" height="200"></canvas>

βš™οΈ Accessing the Canvas Context

To draw on the canvas, you first get its 2D rendering context in JavaScript:

Get 2D Context

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

πŸ–ŒοΈ Drawing Basic Shapes

Here are some simple examples to get you started:

Drawing a Rectangle

// Draw a filled rectangle
ctx.fillStyle = 'skyblue';
ctx.fillRect(50, 50, 150, 100);

Drawing a Circle

// Draw a circle
ctx.beginPath();
ctx.arc(150, 125, 50, 0, Math.PI * 2);
ctx.fillStyle = 'tomato';
ctx.fill();
ctx.closePath();

πŸ–‹οΈ Drawing Lines and Paths

Drawing Lines

ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(200, 100);
ctx.strokeStyle = 'green';
ctx.lineWidth = 4;
ctx.stroke();
ctx.closePath();

πŸ–ΌοΈ Working with Images

You can also draw images on the canvas:

Drawing an Image

const img = new Image();
img.src = 'path/to/image.png';
img.onload = () => {
  ctx.drawImage(img, 0, 0, 300, 150);
};

🎞️ Creating Animations

Use JavaScript functions like requestAnimationFrame() to create smooth animations on canvas.

Basic Animation Example

let x = 0;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
  ctx.fillStyle = 'blue';
  ctx.fillRect(x, 50, 50, 50); // Draw moving square
  x += 2;
  if (x > canvas.width) x = -50;
  requestAnimationFrame(animate);
}
animate();

🧠 Tips & Best Practices

  • Always clear the canvas before redrawing during animations.
  • Use layered canvases for complex effects.
  • Keep performance in mind: limit heavy calculations inside animation loops.
  • Test on different screen sizes and devices.

πŸ”— Useful Resources

>>β€œCanvas lets you paint directly on the web β€” the possibilities are endless!” 🎨