Web Foundations

HTML Canvas

Drawing graphics, animations, charts, and interactive visualizations.

Advertisement

HTML Canvas

Drawing graphics, animations, charts, and interactive visualizations.

Overview

Canvas provides a drawing surface for 2D and 3D graphics.

Key Concepts

  • 2D Context — Drawing API for 2D graphics
  • Drawing Shapes — Rectangles, circles, paths
  • Styling — Colors, gradients, patterns
  • Animations — RequestAnimationFrame loop
  • Event Handling — Mouse and touch interactions

Code Examples

<canvas id="myCanvas" width="800" height="600"></canvas>

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

// Draw rectangle
ctx.fillStyle = '#007bff';
ctx.fillRect(10, 10, 100, 50);

// Draw circle
ctx.beginPath();
ctx.arc(200, 50, 30, 0, Math.PI * 2);
ctx.fillStyle = '#28a745';
ctx.fill();

// Draw line
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(400, 100);
ctx.strokeStyle = '#dc3545';
ctx.lineWidth = 2;
ctx.stroke();

// Draw text
ctx.font = '24px Arial';
ctx.fillStyle = '#333';
ctx.fillText('Hello Canvas!', 10, 150);

// Animation
let x = 0;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  ctx.beginPath();
  ctx.arc(x, 300, 20, 0, Math.PI * 2);
  ctx.fillStyle = '#007bff';
  ctx.fill();
  
  x = (x + 2) % canvas.width;
  requestAnimationFrame(animate);
}
animate();

// Interactive canvas
canvas.addEventListener('click', (e) => {
  const rect = canvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  
  ctx.beginPath();
  ctx.arc(x, y, 10, 0, Math.PI * 2);
  ctx.fillStyle = '#ffc107';
  ctx.fill();
});
</script>

Practice

Build an interactive drawing application with Canvas.

Advertisement